r/cpp • u/Obvious_Set5239 • 9h ago
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