Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between int *x and int* x in C++? [duplicate]

I'm getting back into my C++ studies, and really trying to understand the basics. Pointers have always given me trouble, and I want to make sure I really get it before I carry on and get confused down the road.

Sadly, I've been stymied at the very outset by an inconsistency in the tutorials I'm reading. Some do pointer declarations this way:

int *x

and some do it this way:

int* x

Now the former of the two seems to be by far the most common. Which is upsetting, because the second makes much more sense to me. When I read int *x, I read "Here is an int, and its name is *x", which isn't quite right. But when I read the second, I see "here is an int pointer, and its name is x", which is pretty accurate.

So, before I build my own mental map, is there a functional difference between the two? Am I going to be a leper outcast if I do it the second way?

Thanks.

like image 772
Adam McKeown Avatar asked Apr 10 '13 17:04

Adam McKeown


1 Answers

The famous Bjarne Stroustrup, notable for the creation and the development of the C++, said ...

The choice between "int* p;" and "int *p;" is not about right and wrong, but about style and emphasis. C emphasized expressions; declarations were often considered little more than a necessary evil. C++, on the other hand, has a heavy emphasis on types.

A "typical C programmer" writes "int *p;" and explains it "*p is what is the int" emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A "typical C++ programmer" writes "int* p;" and explains it "p is a pointer to an int" emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.

So, there's no difference. It is just a code style.

From here

like image 116
Thanakron Tandavas Avatar answered Oct 08 '22 15:10

Thanakron Tandavas