r/C_Programming • u/enzodr • Jul 28 '26
Does anyone else dislike pointer declaration?
For reference I am a fourth year computer engineering student. C is my preferred language.
Pointers are declared like this usually:
int *ptr_to_int;
Where the asterisk means it is a “pointer to” the specified type. The asterisk is placed immediately preceding the variable name, with no white peace.
This is what does not make sense to me. I feel that:
int* ptr_to_int;
Is far more clear. The way I see it, the asterisk modifies the type, so therefore it belongs next to the type. Putting it next to the variable name makes me think it is some kind of action or modification to the variable itself.
I think that when using * and & in code, it makes sense to apply it in front of the variable name:
int value = 3;
ptr_to_value = &value;
int copied_value = *ptr_to_value;
It is clear here that syntactically, the * represents something more like an action than a label.
Why is the convention to place the asterisk near variable name, not type? L
40
u/primera_radi Jul 28 '26
I felt that way first too. But consider
int* a, b, c;
vs
int *a, b, c;
The second is much more clear, as only a is a pointer.
Also, now all the names after int evaluate into an int in an expression.
That is, *a evaluates to an int, as do b and c.
6
u/iOSCaleb Jul 28 '26
That's right. Look at it this way... when you have this:
then both
aand*bare of typeint. Putting the*in front of the variable in the declaration mimics the way you use it when you dereference the pointer. The type declaration is telling you that when you dereferencebthe type you'll get isint.75
u/nderflow Jul 28 '26
The language standard and the compiler don't care about the spaces. It's just personal taste.
This is a non-issue really.
44
u/SauntTaunga Jul 28 '26 edited Jul 28 '26
I think of it this way: * is the dereference operator, like () is the function call operator.
int f(); means the result of calling f will be of type int.
Likewise, int *a; means the result of dereferencing a will be of type int.
So, for example, int (*f)(); means that the result of dereferencing f and calling that will be of type int.
int *(*f)(); means dereferencing f calling that and dereferencing the result will be of type int.
10
u/ChickenSpaceProgram Jul 28 '26 edited Jul 28 '26
i just remember that it means that
*ptr_to_intis anint. i feel like theint *ptr_to_int;spacing makes the underlying "declare things how they are used" rule clearer.also, if you declare multiple variables on the same line (which you shouldn't do, but nonetheless), it makes it clearer.
int *foo, bar;declares foo as a pointer-to-intand bar as anint, not both as pointers-to-int.The "declare things how they are used" mentality is anachronistic, but you kinda just have to get used to it. In C the typesystem directs the user towards "how do I make this into a number." Types are less actual types as you'd see in more modern languages and more different kinds and sizes of numbers, aggregates of numbers, different ways to refer to numbers, etc.
18
u/thetraintomars Jul 28 '26
I agree, int* is a type, or should be at least. It’s a different type than int and it should be much clearer. Sure you can write it that way yourself, but all the autoformatters will change it and the compiler doesn’t consistently enforce it with an error if you mix them up. It sure didn’t care back in the 90s which made data structure class a pain in the ass.
5
u/PittLeElder Jul 28 '26
I agree with you, and feel blessed that the people that authored my employers style guide 20 years ago felt the same way.
1
u/thockin Jul 28 '26 edited Jul 28 '26
This is an argument as old as the language. The only justification that holds any water is this:
Obviously
aandcare the same type in the grammar of the language, as arebandd. Butaandcare NOT the same type asbandd. Which of those two lines of code more clearly express that fact?You might also compare with Go, which is C-like from some of the same minds that gave us C:
1
u/DamsLcs4421 Aug 04 '26 edited Aug 04 '26
From a stylistic point of view I agree with you: to me the asterisk placed just before the variable name doesn't feel like "the way to do as intuitively as explicitly". But I'd rather use this convention, "right-to-left reading" (that's how I call it) like so :
int const * const a = &p;It clearly states (from right to left) that
ais a const pointer to a const int. It reveals itself extremely handy when trying to make sense out of monstrous pointers to arrays of lookup tables of some other set of function pointers which themselves return pointers to char* and[...] 🙀😵🫨 You see the point ;)Anyway, as for what you suggested (put the asterisk after the typename), know that I intuitively thought exactly the same at some point, but there's a very good reason not to do it and (even) prefer the good ol' way you don't like (and although figuring it out when you think about it is trivial, it only reveals its trickiness thru time, thru experience, like it happens a few times and you're so done with it you find another better convention that's clear to you and that actually works
Because if you take this habit, you might end up declaring multiple variables in a row like so:
You're screwed cause the pointer declaration operator isn't distributive => unlike multiplication where α×(β+γ) = α×β + α×γ, the pointer marker (*) put once at the beginning doesn't propagate to any other symbols declared within the same statement (= until the semicolon). Only ptrA is a pointer, the B and C ones are plain ints.
You might say that it's obvious and that you wouldn't fall into such confusion, but then what about the other people that are and will be interacting with the code?
If it's juste for yourself then you can use whatever, sometimes I write "dirty" things because it's shorter and does exactly what I need them to do and bc I explicitly understand them. Calling them "dirty" basically says everything: I can't look at them without noticing that it's written in "my" own way, though some might find it cryptic, confusing or even misleading, I know I wouldn't write them like this if it was a shared codebase, and since I also know what what the compiler produces out of these dirty bits of code, I dare to use them bc why the hell not?
Whatever you're gonna opt for, it's a very very old debate that knows no ending :) you can tear it all done to the core to then make an educated choice once and for all, or you can devote your soul to keeping the flame of this debate alive for decades to come, it's up to you :p
Edit: cv-qualifiers aren't distributive either, they have to be stated explicitely for each variable you want them to qualify, if you want to declare say 4 const ints in one line you can't just do:
int const a, b, c, d; // only 'a' is const!3
u/NeuroBill Jul 28 '26
Completely agree. Confused the dickens out of we when I was learning
3
u/Diocles121222 Jul 28 '26
Int* makes perfect sense and any argument about simultaneously declaring multiple variables is irrelevant since it’s not something which should be done in the first place. Int* is the type and it saves a character of typing since it is unambiguous.
For real though, it doesn’t really matter because your actual code should be driven by your coding standards. The more uniform everyone’s code is the better for everyone.
This question makes me think about how the smallest detail is what people get upset about while more important details are set once and ignored.
3
u/xeow Jul 28 '26
Really surprised not to see a single mention of
typedefin here yet.I wouldn't recommend making a habit of
typedefing ordinary pointer types, but if theint *psyntax feels unintuitive while you're learning C, it can help. However, beware thatintptris now its own type alias, sointptr a, b;declares bothaandbas pointers, whereasint *a, b;declares onlyaas a pointer.3
u/i860 Jul 28 '26
Okay, well you're wrong and this horse has been beaten to death countless times already.
3
u/Irverter Jul 28 '26
The problem is that if you do:
a is a pointer and b is an int. Because the * is being applied to the variable and not to the type.
Of course, this is solved with the recommended format of one variable declaration per line, so that it's clear and obvious the inteded behavior and then you can style the pointer declaration as you prefer:
WIth the exception when it's quite obvious variables that go together, like coordinates:
3
u/1v5me Jul 28 '26
It makes no sense at all.
int* a,b,c,whatever; would visually imply that all the vars are pointers.
compared to int *a,b,*c; here *a,*c would more clearly stand out.
As a guy who has done a lot of 2am coding/debugging, multi var declaration is usually an extra pot of coffee.
int *a;
int b,c,d,e;
Is how i normally declare vars, yes i normally gives pointers their own line, coz its just so much easier to spot what is what.
int a,b,c,d,e; // normal temp vars whatever.
int f,g,h;
int *aa;
int *bb;
5
u/LeeHide Jul 28 '26 edited Jul 28 '26
The blind leading the blind a little bit here. Here's how it works in the software engineering industry:
It doesn't matter where you put the
*. Whatever the autoformatter says is how you should do it. If you don't like that, change the autoformatter config.The only time the location matters is when you declare multiple variables on a single line, at which point clang-tidy (and probably other linters) will already point out when you're doing it wrong.
Multiple declarations in a single line also should never be done. Make separate lines, write boring, simple, easy to understand code, always. So in practice, this shouldn't matter to you, though it's good to know the semantics in case you see it in code somewhere.
If your code is clever and there's no measurable reason for it, you have written bad code. You put the
*where your autoformatter says or where your team puts it.The fact that it's a pointer is part of the TYPE. This is true because the type of the variable changes visibly; on your PC, it's likely that
intis 32 bit and fits in a 32 bit register or half a 64 bit register. It occupies 4 bytes on the stack if it gets put on the stack. Add a*, and suddenly it takes up double that (most likely, on your system). This makes it part of the type. It changes the semantics of the type. Not sure what everyone is on about with "it's an action" or "it's a dereference". When you look at the generated IR or machine code, it's part of the type.6
u/djmex99 Jul 28 '26
Totally agree with op
6
u/SmokeMuch7356 Jul 28 '26 edited Aug 03 '26
We declare pointers as
for the exact same reason we don't declare arrays and functions as
After all, "array of
T" and "function returningT" are distinct types as well. It's just that array-ness, pointer-ness, and function-ness are syntactically part of the declarator.EDIT
Since
*can never be part of an identifier, it doesn't matter where the whitespace goes as far as tokenization is concerned. All ofwill yield the same sequence of tokens -
int,*,p,;- and it will always be parsed asThe type "pointer to
int" is specified by the combination of the type specifierintand the declarator*p.Just like the type "5-element array of
int" is specified by the combination of the type specifierintand the declaratora[5]:You do need whitespace between the
intandafor them to be separate tokens, but whitespace doesn't matter for the rest of it:END EDIT
The
T* pstyle only works for simple pointers; it doesn't work for pointers to arrays or pointers to functions:or pointers to arrays of pointers to functions:
(yes, I have used types this obnoxious in the past), and then there's
signal:which reads as
Declaring an array of pointers as
just looks goofy.
And as you point out, in the code we're usually using
*p.*pdoesn't just yield the value of the pointed-to thing, it's an alias for the pointed-to thing; IOW, we can think of*pas an alternate name for something, with*as part of that name.And the
T* pconvention always leads someone to ask whydoesn't declare
qas a pointer.It doesn't match syntax, it doesn't match usage, it introduces confusion, it promotes misunderstanding of how declaration syntax actually works; it's just bad style all the way around.
1
u/Blitzbasher Jul 28 '26
I've always thought of the asterisks as a function that modifies the data type. The "function" isn't connected to the variable itself but the data type.
1
u/therealhdan Jul 28 '26
My college roommate and I got into an argument about this back in the 80's.
He preferred "int* p;"
I explained that that syntax implies "int* a, b;" declares two pointers to int.
His response - "Wait, it doesn't?"
I rested my case.
7
u/Reasonable-Rub2243 Jul 28 '26
I had the same realization when I was a C beginner back in the stone age. You can declare variables as "type* name;" if you like, but there's an issue: you can't declare multiple variables on the same line that way. If you don't mind making a separate line for each variable, go for it.
2
u/tjrileywisc Jul 28 '26
It drives me crazy when people do that, for the bad reason that you're allowed to declare multiple values on a line (bad practice, generally).
You manipulate the variable as a pointer, not as what it is after dereferencing.
2
u/nonchip Jul 28 '26
that's your decision tho.
2
u/AdvancedConfusion752 Jul 28 '26
C is a great language, or probably the greatest language but variable and function declaration is very archaic to today standards. So it is not just the pointers the problem. something like
var x : int
would be more modern.
That being said the way I would read
int *p
is simply "*p" is an int. And "*" only works to pointers. I would not read it "p" is a pointer to int.
2
u/Vesuvius079 Jul 28 '26
I used to feel the same way in C++. I stopped caring after a year or two. You get used to it once there’s actual work to be done.
Semi related: one of my biggest mistakes in my early career with C++ was overusing pointers and the heap. The heap is important but it shouldn’t be your default storage location.
2
u/flatfinger Jul 28 '26
The syntax predates the addition of qualifiers to the language. Something like the Pascal(*) syntax:
to define an array of pointers to integers and a pointer to an array of integers makes clear where "pointer to" fits in a description, and could easily be adapted to include qualifiers, and C's syntax could have easily been adapted to do so if, when typedef and qualifiers were added, a punctuator was added between the type and variables being declared that would be allowable in all cases, and required when using anything other than simple types. Too late now, though.
(*) FWIU, Standard Pascal would require defining custom types for the arrays, but most or all the Pascal implementations I've used extend the language to waive such a requirement--I'm not sure about my C64 Pascal implementation.
2
u/bunkoRtist Jul 28 '26
No you're not alone. It's one of the enduring rough edges of C. Like most have said, unless you declare multiple pointers on the same line, which is almost always bad form, the "more intuitive" spacing works. Back in the day (I only say this because I'm an old head and don't know what they teach anymore), they used to teach the "intuitive" spacing where the pointer is declared as part of the type. If K&R could wave a magic wand I'd bet 3:1 they would change this. But here we are 50-ish years later, thriving anyway. It's not a question of whether C has warts (it has many). It's a question of whether it's still the best tool for the job. Amazingly (and somewhat sadly IMO), the answer is still often "yes". Enjoy!
2
u/Roger01007 Jul 28 '26
Maybe because it allows you to declare pointers and variables of the same type on the same line
2
u/Hawk13424 Jul 28 '26
Problem is the C definition. What is y here?
int* x, y;
2
u/torsten_dev Jul 30 '26
You can get used to either, but all else being equal I would defer to the Linux Kernel style guide, because Kernel code just looks awesome.
3
u/ComplexPeace43 Jul 28 '26
I use
int *ptr_to_intbecause I can clearly read it*ptr_to_int is int, that is, ptr_to_int is a pointer to int.With the former, where for newcomers, they might think it's a type and use
int* ptr_to_int, ptr_to_int1think both are pointers to int, but the latter is just anint. The compiler doesn't care about whitespaces, bothint* pandint *pare parsed asint (*p)that is, the asterisk is bound to the variable.If you use only one declaration per line, then writing
int* p; int* q;makes it easier to read.3
u/Maleficent_Bee196 Jul 28 '26
int * ptr;
2
u/CarlRJ Jul 28 '26 edited Jul 28 '26
For simple syntax (pointer to int, and a single declaration), that works.
As others have pointed out, that breaks down if you have multiple declarations on the same line.
The other thing that will cause havoc with your preferred style is when the declaration isn't simple. Think "pointer to function taking an int and returning a pointer to a character. It's better for consistency's sake to keep the star attached to the name.
There are good reasons why it is done the way it is. What you're suggesting is not "something the developers of C missed".
Learn to read declarations from the inside out, following C operator precedence - in many but not all cases, this will be effectively be right to left - "int *p" is "p is a pointer to an int"
1
u/Ecstatic_Student8854 Jul 28 '26
I had the same initial reaction but there are a few things to consider.
When declaring multiple variables, such as:
int* p1, p2;
The type of p2 is int, not int*. The asterisk kind of binds stronger than the comma.
The way to intuit why this is the case is to think of a declaration `int *p` in a different way.
Think of it like declaring `*p` to be of type int.
1
u/Background_Horse_992 Jul 28 '26
The usual way works well with a certain way of determining more complex types. The left side being simple like an int, and the right side demonstrating the operations to be performed on the type to get an int. In this case, I would read the usual declaration in my head as “dereferencing ptr_to_int will give me an int”
1
u/QuirkyXoo Jul 28 '26
I think this kind of pointless, byzantine questions is what makes people avoid participating in this sub.
1
u/Disastrous-Team-6431 Jul 28 '26
It makes sense on C imo - "a is an int". But in c++, it collapses when we do eg std::vector<int>. Not a huge problem either way.
1
u/Migazul8 Jul 28 '26
I always declare them the second way
1
u/TheLimeyCanuck Jul 28 '26 edited Jul 28 '26
You aren't forced to declare it that way, it's just convention. The parser happily accepts
int* varname;, which is how I always declare it for precisely the reason you describe.For anybody who says, yeah but I can do
int x, *y;... WTH are you making your code harder to read? Put each degree of referencing on its own line.1
u/anhadsa Jul 28 '26
From my understanding, the declaration mimics the usage, so take int (*ptr)[5), lets say temp is *ptr, we effectively have int temp[5], meaning deref gives an array 5 ints, its quite nice when you embrace its memetic usage, stuff like this makes sense for example int * (*p)[5], this would be considered a pointer to an array of 5 elements in which each element is a pointer to an in, so effectively you deref once you get an array, int *temp[5], and now if you deref this again, (an element of the array to be exact) you get an int. I used to dislike it but now I like it.
1
u/moocat Jul 28 '26
That is strictly a style issue, both are legal and the compiler treats them identically. I'm not sure which is most common these days but I've been using Google style for the last too many years and it does
type* ptr.While you can use whichever one you prefer, I recommend that you become comfortable with both. Assuming you are going to work in industry, you'll have a team style to follow and you may not agree with every decision but you'll need to learn just to go with it.
1
u/TransientVoltage409 Jul 28 '26
My personal convention is to declare as
int * p;, the asterisk isolated with spaces on both sides. In the dereferencing it's*p.But don't worry, you can always fix it with a custom type.
typedef int * intptr;. Now you can avoid the mess of mixing int with int* in the same declaration, and no more messy asterisks either.[Is it /s? Could be.]
1
u/sky5walk Jul 28 '26
C should have demanded the pointer variable *myvar had the asterisk stuck to it throughout the source code! That would save me constantly double checking old code.
I always stick to one way: int *myvar;
1
u/Jbolt3737 Jul 28 '26
I do
int * ptr_to_int;1
u/White_C4 Jul 28 '26
I think generally a lot of people would agree with the asterisk being placed after the type rather than before the variable name. Even languages after C with explicit pointers adhere to that idea.
1
u/Neither_Berry_100 Jul 28 '26
I coded c++ at work around 15 years ago. It is fine the language works. I don't understand the newer allocations in the later versions though. And I don't know why they changed it when it was fine the way it is.
1
u/Spirited-Candy1981 Jul 28 '26
That's the way I always declare them, with the asterisk glommed onto the type. If I needed to do anything more complicated, I'd declare subtypes using typedefs to make it more clear/clean.
1
u/cosiekvfj Jul 29 '26
Yes, my preference is int* ptr;
and disallowing declaring multiple pointers on the same line. basically
int *ptr1, *ptr2;
vs
int* ptr1;
int* ptr2;
because I want it more consistent with casts (void*) vs (void *)
1
u/mymindisagarden Jul 29 '26
same applies to array declarations [] and function declarations (). It is done that way such that declarations mimics usage.
1
u/NoSpite4410 Jul 29 '26
This is not an uncommon pet peeve. In many code bases , particularly low-level libraries, it is the convention to create a "companion pointer type" for structures and pointers to arrays and such with a typedef.
Often when declaring a struct, you want to declare a pointer to it at the same time for malloc.
POSIX formally reserves the
_tsuffix only for system-defined types, so its possible to duplicate it in your own code. In that case you can use a_ptrsuffix or something.1
u/HausOfSun Jul 31 '26
You are right. Also pointers are an invitation to memory leaks. How about a pointer system that only points to allotted memory controlled by the app & automatically prevents overruns.
1
u/EclipsedPal Jul 31 '26
Doesn't matter where you put the asterisc, just be mindful that
int* a, b;
doesn't declare two pointers; ;)
But declaring multiple variables on the same line is a very bad practice anyway imho.
1
u/questron64 Aug 02 '26
The convention is because it's part of the declarator and not the type. It's a bit of a moot point because in except in for loop declarations you shouldn't be declaring a pointer and another variable in the same declaration. It helped avoid errors like this, where it appears a and b are both pointers, but a is a pointer and b is an int. But in 2026 you should not be doing this anyway.
While pointer syntax can be a bit of a sticking point in C, there's little point in complaining about it. You're 50 years too late for that. You just learn it and move on.
0
u/Former-Print7759 Jul 28 '26 edited Jul 28 '26
The thing is that you declare which type will expression have. So
int *a
Should be read as:
When I use *a in code then it has int type
That’s something backwards type of thinking about it, for sure
But, compare
int f(double);
It clearly says that f receives double and returns int. I mean, when you apply f to some double then you get int (as declared)
The same is for int *a
When you apply * to a then you receive int
0
u/Reasonable_Ant4397 Jul 28 '26
I 100% agree. I'm not a CS person but do like coding and found your preferred syntax to be far more helpful when learning what c does. Having the * on two different places infers different operations, or at least or did to me to begin with.
0
u/EmbedSoftwareEng Jul 28 '26
It's a recurring fantasy of mine to build a time machine and go back in time and force K&R to use the @ sign for pointers, instead of *, which is already doing multiplication duties.
Other than that, I just employ a style where the * is separated from the variable name by one space at declaration time, and without the space when the variable is being dereferenced. There's nothing wrong with applying the * to the end of the pointed to type name, but most style guides that I've ever had to work to do not do it that way. Think of the * as another storage class modifier, but one that goes after, not before the base type.
I think it's the very fact that the dereferencing * has to be associated with the variable name when it appears as an argument to in the RHS of an assignment is precisely why most people associate them at the point of declaration.
Also, most style guides I work to also promote prefixing variable names with tags to indicate some kind of typing information, so I wouldn't do:
uint32_t * word;
I would do
uint32_t * p_word;
to emphasize that where ever it's used, p_word is a pointer to something. The rest of the name after the p_ should make it obvious what that something being pointed to is.
This can get muddled, because I often find up with a * declared pointer variable, but if I use it more with array notation, then p_word[i] starts to get a bit busy. So, even if I have a * declared pointer variable, if I use it in an array-like manner, I leave the p_ part off of the variable name.
-5
u/Kadabrium Jul 28 '26
int *x means to me: this is an int and its passing mode is pass by pointer.
0
u/[deleted] Jul 28 '26
[deleted] — view deleted comment
0
u/[deleted] Jul 28 '26
[removed] — view removed comment
0
u/[deleted] Jul 28 '26
[deleted] — view deleted comment