r/cpp • u/Obvious_Set5239 • Aug 30 '26
The weirdest behavior in C++ that came from C
If you're trying to define two pointers in a single statement (what is in general a bad idea), you may want to do it like this:
#include <print>
int main()
{
int x = 10;
int* a, b;
a = &x;
b = &x;
std::println("a={:#x}, b={:#x}", uintptr_t(a), uintptr_t(b));
}However, it doesn't work as you expect, and won't compile. Because int* a, b; declares only a as int*; b, and all the rest variables will be int. The correct one-statement declaration of two pointers is int* a, * b;
main.cpp:8:9: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
8 | b = &x;
| ^~
| |
| int*b has type int
This behavior is the reason why some people prefer putting the asterisk next to the variable name, not next to the type
I can understand the logic, that C authors had while making this syntax. It's a sort of reversive/deduction logic. You kinda declare what type it will be after using the dereference * operator, instead of declaring the type being a pointer itself. But I find this logic very-very strange, and overthought
The funny thing, that even the compiler in the error message above, treats * as a sort of type modifier, that is inseparable from int. But, apparently, the C creators had a completely different vision on what pointers are
I personally don't think that this behavior justifies reteaching yourself to write * in front of variable names, and especially in front of function names. I think it's just a not well-thought decision made very long ago in 1970s
53
u/mr_seeker Aug 30 '26
That's why you should not more than one per line:
14
u/Supadoplex Aug 30 '26 edited Aug 30 '26
I dont think they had a completely different idea of what pointers are. I cannot know what the were thinking, but perhaps their idea was simply that following is a super expressive, concise and convenient way to write a common pattern:
35
u/Beneficial_Steak_945 Aug 30 '26
C++ should just deprecate defining more than one variable in one go this way.
5
u/Sensitive-Talk9616 Aug 30 '26
Yeah, it's very much a C coding pattern - declare all variables in bulk at the start.
Ideally, in C++, one would only declare variables where needed, so temporaries should just be directly defined. Even better if they can be scoped so that lifetimes are easier to reason with.
I wouldn't be mad if they simply disallowed declaring multiple variables in a single statement.
4
u/FallenDeathWarrior Aug 30 '26
I had that discussion with my colleagues what coding style should be used. And they used that example why you shouldn't put the pointer next to the type instead move it to the variable name.
9
u/tstanisl Aug 30 '26
It's not a different understanding but rather a different convention.
Means that
a,*b,**c,d()returnsint.5
u/QuentinUK Aug 30 '26 edited Oct 18 '26
Interesting!
2
u/SmokeMuch7356 Aug 30 '26 edited Aug 30 '26
As I've said a hundred times, we declare pointers as
for the exact same reason we don't declare arrays and functions as
Array-ness, function-ness, and pointer-ness are all specified as part of the declarator. This quickly becomes obvious when dealing with pointers to arrays and functions:
or even more complex types:
The same is true of references, btw; they should be declared as
T &rfor all the same reasons.EDIT
And the point I keep intending to make and never remember is that I'm less interested in the type of
pthan I am of*p;*pis the thing I'm reading and writing to:The expression
*pacts as a name for an object, and the type of that object isT. From that perspective,T *pfeels more natural.Yeah yeah yeah, references and smart pointers have obviated the need for raw pointers in the vast majority of circumstances. But if you're gonna use raw pointers for whatever reason, the
T *pconvention will more clearly convey intent and create less confusion in the end.1
u/SamuraiGoblin Aug 30 '26
Yes, I once asked whether people preferred 'int* a' or 'int *a' and got heavily downvoted.
I think it's a valid question, and it doesn't have a simple answer. It's confusing to beginners and it depends on where and how it is used.
1
u/geon Aug 30 '26
Your formatting is off. It should be
int *a, b;
Not
int* a, b;
2
u/Business-Decision719 Aug 30 '26 edited Aug 30 '26
You're right. This is a really counterintuitive decision C made and C++ inherited. Effectively
*is a generic type; it's a pointer, but it needs another type to specify what it's pointing. The*should always attach to its type parameter to generate a new combined type name, but in variable declarations it attaches to the variable name to modify that one variable's type instead.The same problem exists with arrays.
Granted, it's more obvious that only one variable is an array, because the brackets are always separated from the item type and have to go after each individual array variable, but separating the brackets from their type parameter is already bad enough. Then there's array-to-pointer decay which its own abomination.
C's declaration syntax for pointers and arrays is just horrible, and it's one of many problems C++'s containers and smart pointers mitigate very nicely. There's a type
int, a typestd::shared_ptr<int>, a typestd::array<int>, and many more types that could take anintparameter with identical angle-bracket syntax. You can also have astd::shared_ptr<std::array<int, 10>>, keeping pointers and containers orthogonal.2
u/DreamingPeaceful-122 Aug 30 '26
I talked about this in my first SWE job with my coworker. I totally agree about your point.
2
u/NilacTheGrim Aug 30 '26
Confusion what would not have arisen had you been doing the cromulent thing of writing it as
Type *varrather thanType* var.;P
2
u/QuirkyXoo Aug 30 '26
No, it's not weird or a bad idea, it's just you not knowing the C syntax.
1
u/Raknarg Aug 31 '26
ah yeah. I ran into that bug once and ever since I have never done a compound declaration statement. If it wasn't for the legacy code that would break I would say they should just make it illegal at this point lol
1
u/PrimozDelux Sep 02 '26 edited Sep 02 '26
I think this is the worst mistake in the design of C. Probably makes more sense when considering they wanted to standardize a portable assembly language, so I don't fault the authors. On the other hand I do fault people who defend it ante domini 2026
1
u/mredding Sep 02 '26
I wouldn't agree that this statement is close enough to call correct, but mostly because the surrounding context of your paragraph I cut out suggests a bit more uncertainty. The design principle is actually well documented, so there doesn't have to be any doubt or question.
The guiding C language design principle that got us here is "declarations match use" - that variable declaration looks like an expression that uses that variable.
This reads: "The evaluated expression
*aresults in anint, the evaluated expressionbresults in anint."I agree, but C was devised before I was born, so I benefit from hindsight. I think we can agree - though not everyone, that this design principle perhaps didn't age well. I bet it felt a lot better in the punch-card era.
Well that's because it is a type modifier, and in a way it's inseparable from
int, but bound to the variable.Back to the guiding principle, K&R had a different vision on what a type declaration is.
Your position is a popular one I will never understand. It's like cutting against the grain. The language has spoken. The type is bound to the variable, so bias toward the variable.
Overall, I consider the ANCIENT flame war of where to stick your asterisk moot; A) we have code beautifiers - clang-format and forget. B) we have an in-language solution to this problem - type aliases:
It does exactly what you think it will.
I think this is the language telling you how to write code. The left/right type/variable syntax is intuitive to us, so use the tools the language provided to lean into that. The alias encapsulates the type into a single unit, and binds THAT to the variable. Templates can create aliases, so you can even generate these things, that's a lot of what we do with type traits.
0
u/kevleyski Aug 30 '26
Common bug and why better to separate definitions b needs *
-1
u/AnyPhotograph7804 Aug 30 '26
Yes. When C was invented, even storing sourcecode was not so cheap. And this is the reason why there are so many shortcuts in C like implicit conversions etc. because it saves storage space. And at that time, stuff like implicit conversions was not considered as a potential source of errors. Because the apps did not have millions LOC and hundreds of developers working on one application.
And because C++ is based on C, it inherits all these little quirks. The only thing, you can do, is enable all warnings and treat them like compiler errors.
-3
u/knouqs Aug 30 '26
The idea for a lot of decisions in C from that time stemmed from space constraints and "That's how we did it in B." Memory was much more expensive and savings like not repeating the base type were cost-effective. Other decisions like having default fall-through for case blocks in switch statements are known design mistakes. It happens. We get to live with the effects of them and become better developers for the effort.
0
u/[deleted] Aug 30 '26
[deleted] — view deleted comment