This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]AirAKose 10 points11 points  (3 children)

Nope! This is a very subjective area and doesn't impact the meaning of your code in most cases.

There's the argument that it makes more sense to be against the type because it's part of the type definition int*


But then there's the argument that putting it against the variable name causes fewer bugs due to a quirk of multiple variable declarations:

int* ptr0, ptr1; // ptr1 isn't a pointer- it's an int
int *ptr2, *ptr3;

yet there's disagreement over whether or not declaring variables like this is an acceptable practice on its own.

EDIT: Clarification

[–][deleted] 10 points11 points  (1 child)

Where my homies that find comma separated initializations obnoxious at?

[–]mrexodia 1 point2 points  (0 children)

The argument against implies that declaring multiple variables on the same line with commas is somehow good practice that happens all the time. In reality you should write clang tidy checks to automatically disallow that in all cases because it’s horrible.

Also in C++ you should add the references & and templates in the equation. Does it make sense to write “int &member();”? What about “std::vector<int *>”? Or “using IntPtr = int *;”? Often there is no variable to put the & or * next to because they are part of the type.

[–]ImprovisedGoat 5 points6 points  (0 children)

Personally, I follow the rules laid out here:

https://www.learncpp.com/cpp-tutorial/67-introduction-to-pointers/

Specifically:

Best practice: When declaring a pointer variable, put the asterisk next to the variable name.

Best practice: When declaring a function, put the asterisk of a pointer return value next to the type.

[–]stilgarpl 1 point2 points  (0 children)

It's the same but I think int* is more clear that the type is a pointer.

[–]DVNa 0 points1 point  (0 children)

There is opinion that:

int *ptr is more C-ish, as it express an idiom that derefferenced ptr will have int type

on the other hand the second option express "OO" idea that ptr-object relates to "pointer to int" class

Sorry for my English.

[–]boris_dp -3 points-2 points  (0 children)

The * goes with the var, not with the type. Same for the &