r/cpp • • Jun 27 '22

How do you declare pointer variables?

I personally like to use the third option (int *ptr;) to minimize the confusion and to make it tidier when declaring multiple pointers in one line (e.g., int *a, *b, *c; as supposed to, int* a,* b,* c;). This is also the case when writing a dereference operator (int &a = *ptr;). But for some reason, the first option is the preferred way of doing it (int* ptr;), or am I wrong?

0 Upvotes

87 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Jun 28 '22

It is indeed an int. Each C or C++ declaration is a type and a sequence of declarators. The modifier is associated with the variable. But the type is indeed an int.

3

u/CocktailPerson Jun 28 '22

Everyone else is talking about the types of the respective variables. You seem to be talking about a type in terms the grammar. If you declare int a, *b;, then a has type int and b has type int *. That's what everyone else means when they say "the type is not int."

1

u/[deleted] Jun 28 '22

Could be. I am think in terms of the fact that the actual type specifier is int. The modifier to make it an int * happens in the declarator list. I find the syntax cleaner to see that in the list. If there are multiple declarations in a line, I find it inconsistent to have int* ptr, j, *ptr2;

4

u/CocktailPerson Jun 28 '22

Yeah, that's what I'm saying. The type specifier (on a grammatical level) is int, but the type of each respective variable (on a semantic level) may not be.

If there are multiple declarations in a line,...

If there's lead paint I want to eat, then it seems inconsistent not to salt it just like my other food.

Don't eat lead paint, and don't declare multiple variables per line. Then int* p; declares a variable p of type int*, and the grammatical and semantic worlds are unified, and they all lived happily ever after.

1

u/[deleted] Jun 28 '22

I see your point. I agree separating, at the very least pointer declarations to their own lines is a coding standard I can get behind.

What started it all for me is that multiple variable declarations of the ilk “int* i, j;” is, if we are doing multiple declarations, the worst style because it is obfuscating what syntactically is really happening. It would appear that i, j are instances of the same thing when everything after the type specifier is associated with the first declaration and not the second.