Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter where I place the asterisk when declaring pointers in C++?

I'm just learning C++ and from all the example code I have looked at over the past few days I am having a hard time understanding where the pointer should be placed.

What's the difference in these 3?

1. char* x = /* ... */
2. char *y = /* ... */
3. char * z = /* ... */

Or

1. ClassX* x = /* ... */
2. ClassY *y = /* ... */
3. ClassZ * z = /* ... */

Thanks for your help.

like image 951
user678994 Avatar asked Mar 27 '11 14:03

user678994


People also ask

Where do you put an asterisk for pointers?

When declaring a pointer type, place the asterisk next to the type name. Although you generally should not declare multiple variables on a single line, if you do, the asterisk has to be included with each variable.

Which is the correct way to declare a pointer in C?

First, declaring a pointer variable: char *ptr; This declaration tells us the pointer type (char), pointer level ( * ), and variable name ( ptr ).

What does * do in pointers?

If you see the * in a declaration statement, with a type in front of the *, a pointer is being declared for the first time. AFTER that, when you see the * on the pointer name, you are dereferencing the pointer to get to the target.

What does * indicate in pointer in C?

A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.


2 Answers

There's no difference. They're exactly the same.

You can choose to write it however you like. Typically, C++ programmers place the asterisk next to the type, while it is more common for C programmers to place the asterisk next to the name of the variable.

The only pitfall to be aware of is when you declare multiple variables on a single line (which you really shouldn't do anyway, if not for precisely this reason). For example, in the following statement, only variable x is declared as a pointer:

char* x, y;

Compare that with the following, which makes it much more clear which variables are pointers:

char *x, y;

As best I can tell, the third syntax emerged as a poor compromise between the two leading options. Instead of placing the asterisk next to one or the other, someone decided to place it in the middle, which is about the only place it decidedly does not belong.

like image 157
Cody Gray Avatar answered Oct 04 '22 20:10

Cody Gray


no difference, but you must pay attention that if you write:

char* x, y;

only x is a pointer (the first variable declared) and you should reference them this way:

x = new (char);
*x = 'a';
y = 'b';
like image 28
Alina Danila Avatar answered Oct 04 '22 21:10

Alina Danila