This question already has answers here:
Placement of the asterisk in pointer declarations
(14 answers)
Difference between int* p and int *p declaration [duplicate]
(3 answers)
difference between int* i and int *i
(9 answers)
Closed 4 years ago.
What is the most proper way to place asterisk? Why?
1) type* var;
2) type *var;
It does not matter as far as you are declaring only one pointer. It is usually writen like in the second example (in the code I usually read/write) but for the compiler it's the same.
The trouble can come out if you are declaring more than one pointer. For example, this is not declaring two pointer, instead it declares one pointer and one var of type type.
type* var1, var2;
You need to do instead:
type* var1, *var2;
I prefer to use the * by the var always.
Pointer is the type, and I think it makes most sense to group the type information:
int* foo;
This can lead to confusion if several variables are defined on the same line:
int* foo, bar; // foo will be int*, bar will be int
The solution to this is, never declare several variables on the same line. Something that Code Complete advocates, anyway.
Both work. I'd argue that #1 is clearer in general, but misleading in C and can lead to errors, e.g.:
type* var1, var2;
// This actually means:
type *var1;
type var2;
So I'd say that #2 is more idiomatic in C and therefore recommended, especially if you are not the only programmer working on the code (unless, of course, you all agree on a style).
As others have pointed out, both work fine, and the wrong one actually has the advantage of syntactic economy.
The way I look at it, a declaration consists of type followed by the variable.
<type> <variable>;
int ii;
int* pii;
So, if you take away the variable, what remains is the type. Which is int and int* above. The compiler treats int* as a type internally (which is pointer to an int).
C, unfortunately, does not support this syntax seamlessly. When declaring multiple variables of the same type, you should be able to do this:
<type> <variable>, <variable>, <variable>;
which you cannot with a pointer type:
int* ii1, ii2, ii3;
declares ii1 of type int* and the rest of type int. To avoid this, I make it a habit of declaring only one variable per line.
I've heard it argued that technically the * is a modifier to the variable,
and this is evidenced by the need to use * multiple times in multi variable
declarations
eg. int *p, *q, *r;
However I like to think of it as a modifier to the base type because that
is what appears in prototypes.
eg. void func(int*);
.PMCD.
PS. I know I haven't helped your problem :)
The second mode is correct. The other mode are not so clear for a novice programmer.
The form int* variable is usually discouraged
That would rather be a coder's preference.
For me, I declare pointers by:
int * var1, var2;
Wherein var1 is a pointer, and var2 is not. If you want to declare multiple pointers in a line:
int * var1, * var2;
And of course, using the other ways are valid.
Declaration semantics follow expression semantics (specifically operator precedence) and I find more complex declarations easier to read using the second style.
You can think of
int *foo;
declaring the type of the expression *foo (ie indirection operator applied to foo) to be int instead of foo being declared to be of type int *.
Whatever convention you choose, just try to be consistent.
There is no single "most proper place".
Usually it is the place the rest of the code uses.
If you're writing your own code from the beginning and can choose your own convention: choose your own convention and stick with it.
If you choose something other than type * var you will meet 'awkward' situations:
/* write these with another style */
int * var;
int const * var;
int * restrict var;
PS. It shouldn't matter, but I usually use type *var;
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
This is not a duplicate of this question
I understand why it is better to declare variables like this:
int *var;
instead of
int* var
I understand that this avoids the ambiguous case of
int* var1, var2 where it would seem that var1 and var2 are both pointers to integers, but var2 is actually just a regular integer.
My question is why int* var1, var2 doesn't declare both variables as pointers to integers. Intuitively, I would think that int* would act like any other data type, where you would just have to use int* var1, var2 to declare both variables of type int*. In other words, why is C designed so that each variable needs an asterisk before it?
Intuitively, I would think that int* would act like any other data type
If you want to become comfortable with C, you may need to adjust your intuition! Types are at least a little bit complicated; in fact the type system is a lot like a little programming language of its own! int is a type, but "pointer" is a meta-type. You can have pointers to anything, even pointers to pointers.
In other words, why is C designed so that each [pointer] variable needs an asterisk before it?
Because, as explained in several of the answers to that other question, the scheme is that a declaration contains a "base type" and then some "declarators". In the case of arrays, pointers, and functions, the "declarator" is a little sample of whatever thing is going to have the base type. If I say
int i;
the declarator is just i, so I'm saying that i is going to be an int. No mystery there. But if I say
int a[10];
I'm saying that one element of the array I'm declaring — that is, when I later use the array by saying something like a[i] — is going to be an int. If I say
int f();
I'm saying that calling the function is going to return an int.
Finally, if I say
int *ip;
I'm saying that when I take the contents of this pointer, using the expression *ip, then what *ip is going to be is an int.
And of course I can string these together on the same line:
int i, a[10], f(), *ip;
Now, perhaps I'm just rehashing the answers at the other question, and not explaining why things were set up this way. The reason is that it makes it possible to declare arbitrarily-complicated derived types. We can have arrays, and pointers, and functions, and arrays of arrays, and pointers to arrays, and functions returning pointers, and pointers to functions, and arrays of pointers to functions, and functions returning pointers to functions, and types even more numerous and complicated than those, and they can all be declared (in a general and open-ended way) using the same sort of concise, punctuation-rich, unwordy syntax that C is famous for
I don't think it would have been possible to design a type system that could have expressed the concept of "array of pointers to functions" on the left, leaving you to just put the variable name on the right. Or, if you could design such a system, it would have been complicated and confusing and cumbersome to use, even more complicated and confusing than C's present scheme seems to you, with its odd combination of type names on the left, and declarators — with their mixture of names, asterisks, and other punctuation — on the right.
See also Question 1.21 in the C FAQ list.
Or, perhaps I lied. I just said, "I don't think it would have been possible to design a type system that could have expressed [complicated things] on the left, leaving you to just put the variable name on the right." But, in fact, C's typedef facility lets you do precisely that, if you want to build up a complex type in stages.
For example, if you say
typedef int *pointer_to_int;
you have arranged that the identifier pointer_to_int is not an actual variable of type int *, but rather, a synonym for the type int *. Having done that, you can declare several integer pointers at once, without having to re-type those pesky asterisks:
pointer_to_int p1, p2, p3; /* just like int *p1, *p2, *p3; */
And it works for more complicated types, too. I can say
typedef int *(*pointer_to_function_returning_pointer_to_int)();
and then do
pointer_to_function_returning_pointer_to_int x1, x2, x3;
at which point x1, x2, and x3 are all pointers to functions returning pointers to int, just as if I'd said
int *(*x1)(), *(*x2)(), *(*x3)();
In fact, the CS50 course introduces a "handy" typedef
typedef char *string;
which makes the identifier string be an alias for the type "pointer to char", which allegedly makes it easier for beginners to declare lots of strings. Unfortunately, char * isn't really C's One True String type, so the string typedef probably causes as much confusion as it attempts to resolve. (Part of the problem is that pointers do not necessarily make good "opaque" types. If you're dealing with a pointer, you often need to know that you're dealing with a pointer, so hiding it behind a typedef doesn't help.)
Why do most C programmers name variables like this:
int *myVariable;
rather than like this:
int* myVariable;
Both are valid. It seems to me that the asterisk is a part of the type, not a part of the variable name. Can anyone explain this logic?
They are EXACTLY equivalent.
However, in
int *myVariable, myVariable2;
It seems obvious that myVariable has type int*, while myVariable2 has type int.
In
int* myVariable, myVariable2;
it may seem obvious that both are of type int*, but that is not correct as myVariable2 has type int.
Therefore, the first programming style is more intuitive.
If you look at it another way, *myVariable is of type int, which makes some sense.
Something nobody has mentioned here so far is that this asterisk is actually the "dereference operator" in C.
*a = 10;
The line above doesn't mean I want to assign 10 to a, it means I want to assign 10 to whatever memory location a points to. And I have never seen anyone writing
* a = 10;
have you? So the dereference operator is pretty much always written without a space. This is probably to distinguish it from a multiplication broken across multiple lines:
x = a * b * c * d
* e * f * g;
Here *e would be misleading, wouldn't it?
Okay, now what does the following line actually mean:
int *a;
Most people would say:
It means that a is a pointer to an int value.
This is technically correct, most people like to see/read it that way and that is the way how modern C standards would define it (note that language C itself predates all the ANSI and ISO standards). But it's not the only way to look at it. You can also read this line as follows:
The dereferenced value of a is of type int.
So in fact the asterisk in this declaration can also be seen as a dereference operator, which also explains its placement. And that a is a pointer is not really declared at all, it's implicit by the fact, that the only thing you can actually dereference is a pointer.
The C standard only defines two meanings to the * operator:
indirection operator
multiplication operator
And indirection is just a single meaning, there is no extra meaning for declaring a pointer, there is just indirection, which is what the dereference operation does, it performs an indirect access, so also within a statement like int *a; this is an indirect access (* means indirect access) and thus the second statement above is much closer to the standard than the first one is.
Because the * in that line binds more closely to the variable than to the type:
int* varA, varB; // This is misleading
As #Lundin points out below, const adds even more subtleties to think about. You can entirely sidestep this by declaring one variable per line, which is never ambiguous:
int* varA;
int varB;
The balance between clear code and concise code is hard to strike — a dozen redundant lines of int a; isn't good either. Still, I default to one declaration per line and worry about combining code later.
I'm going to go out on a limb here and say that there is a straight answer to this question, both for variable declarations and for parameter and return types, which is that the asterisk should go next to the name: int *myVariable;. To appreciate why, look at how you declare other types of symbol in C:
int my_function(int arg); for a function;
float my_array[3] for an array.
The general pattern, referred to as declaration follows use, is that the type of a symbol is split up into the part before the name, and the parts around the name, and these parts around the name mimic the syntax you would use to get a value of the type on the left:
int a_return_value = my_function(729);
float an_element = my_array[2];
and: int copy_of_value = *myVariable;.
C++ throws a spanner in the works with references, because the syntax at the point where you use references is identical to that of value types, so you could argue that C++ takes a different approach to C. On the other hand, C++ retains the same behaviour of C in the case of pointers, so references really stand as the odd one out in this respect.
A great guru once said "Read it the way of the compiler, you must."
http://www.drdobbs.com/conversationsa-midsummer-nights-madness/184403835
Granted this was on the topic of const placement, but the same rule applies here.
The compiler reads it as:
int (*a);
not as:
(int*) a;
If you get into the habit of placing the star next to the variable, it will make your declarations easier to read. It also avoids eyesores such as:
int* a[10];
-- Edit --
To explain exactly what I mean when I say it's parsed as int (*a), that means that * binds more tightly to a than it does to int, in very much the manner that in the expression 4 + 3 * 7 3 binds more tightly to 7 than it does to 4 due to the higher precedence of *.
With apologies for the ascii art, a synopsis of the A.S.T. for parsing int *a looks roughly like this:
Declaration
/ \
/ \
Declaration- Init-
Secifiers Declarator-
| List
| |
| ...
"int" |
Declarator
/ \
/ ...
Pointer \
| Identifier
| |
"*" |
"a"
As is clearly shown, * binds more tightly to a since their common ancestor is Declarator, while you need to go all the way up the tree to Declaration to find a common ancestor that involves the int.
That's just a matter of preference.
When you read the code, distinguishing between variables and pointers is easier in the second case, but it may lead to confusion when you are putting both variables and pointers of a common type in a single line (which itself is often discouraged by project guidelines, because decreases readability).
I prefer to declare pointers with their corresponding sign next to type name, e.g.
int* pMyPointer;
People who prefer int* x; are trying to force their code into a fictional world where the type is on the left and the identifier (name) is on the right.
I say "fictional" because:
In C and C++, in the general case, the declared identifier is surrounded by the type information.
That may sound crazy, but you know it to be true. Here are some examples:
int main(int argc, char *argv[]) means "main is a function that takes an int and an array of pointers to char and returns an int." In other words, most of the type information is on the right. Some people think function declarations don't count because they're somehow "special." OK, let's try a variable.
void (*fn)(int) means fn is a pointer to a function that takes an int and returns nothing.
int a[10] declares 'a' as an array of 10 ints.
pixel bitmap[height][width].
Clearly, I've cherry-picked examples that have a lot of type info on the right to make my point. There are lots of declarations where most--if not all--of the type is on the left, like struct { int x; int y; } center.
This declaration syntax grew out of K&R's desire to have declarations reflect the usage. Reading simple declarations is intuitive, and reading more complex ones can be mastered by learning the right-left-right rule (sometimes call the spiral rule or just the right-left rule).
C is simple enough that many C programmers embrace this style and write simple declarations as int *p.
In C++, the syntax got a little more complex (with classes, references, templates, enum classes), and, as a reaction to that complexity, you'll see more effort into separating the type from the identifier in many declarations. In other words, you might see see more of int* p-style declarations if you check out a large swath of C++ code.
In either language, you can always have the type on the left side of variable declarations by (1) never declaring multiple variables in the same statement, and (2) making use of typedefs (or alias declarations, which, ironically, put the alias identifiers to the left of types). For example:
typedef int array_of_10_ints[10];
array_of_10_ints a;
A lot of the arguments in this topic are plain subjective and the argument about "the star binds to the variable name" is naive. Here's a few arguments that aren't just opinions:
The forgotten pointer type qualifiers
Formally, the "star" neither belongs to the type nor to the variable name, it is part of its own grammatical item named pointer. The formal C syntax (ISO 9899:2018) is:
(6.7) declaration:
declaration-specifiers init-declarator-listopt ;
Where declaration-specifiers contains the type (and storage), and the init-declarator-list contains the pointer and the variable name. Which we see if we dissect this declarator list syntax further:
(6.7.6) declarator:
pointeropt direct-declarator
...
(6.7.6) pointer:
* type-qualifier-listopt
* type-qualifier-listopt pointer
Where a declarator is the whole declaration, a direct-declarator is the identifier (variable name), and a pointer is the star followed by an optional type qualifier list belonging to the pointer itself.
What makes the various style arguments about "the star belongs to the variable" inconsistent, is that they have forgotten about these pointer type qualifiers. int* const x, int *const x or int*const x?
Consider int *const a, b;, what are the types of a and b? Not so obvious that "the star belongs to the variable" any longer. Rather, one would start to ponder where the const belongs to.
You can definitely make a sound argument that the star belongs to the pointer type qualifier, but not much beyond that.
The type qualifier list for the pointer can cause problems for those using the int *a style. Those who use pointers inside a typedef (which we shouldn't, very bad practice!) and think "the star belongs to the variable name" tend to write this very subtle bug:
/*** bad code, don't do this ***/
typedef int *bad_idea_t;
...
void func (const bad_idea_t *foo);
This compiles cleanly. Now you might think the code is made const correct. Not so! This code is accidentally a faked const correctness.
The type of foo is actually int*const* - the outer most pointer was made read-only, not the pointed at data. So inside this function we can do **foo = n; and it will change the variable value in the caller.
This is because in the expression const bad_idea_t *foo, the * does not belong to the variable name here! In pseudo code, this parameter declaration is to be read as const (bad_idea_t *) foo and not as (const bad_idea_t) *foo. The star belongs to the hidden pointer type in this case - the type is a pointer and a const-qualified pointer is written as *const.
But then the root of the problem in the above example is the practice of hiding pointers behind a typedef and not the * style.
Regarding declaration of multiple variables on a single line
Declaring multiple variables on a single line is widely recognized as bad practice1). CERT-C sums it up nicely as:
DCL04-C. Do not declare more than one variable per declaration
Just reading the English, then common sense agrees that a declaration should be one declaration.
And it doesn't matter if the variables are pointers or not. Declaring each variable on a single line makes the code clearer in almost every case.
So the argument about the programmer getting confused over int* a, b is bad. The root of the problem is the use of multiple declarators, not the placement of the *. Regardless of style, you should be writing this instead:
int* a; // or int *a
int b;
Another sound but subjective argument would be that given int* a the type of a is without question int* and so the star belongs with the type qualifier.
But basically my conclusion is that many of the arguments posted here are just subjective and naive. You can't really make a valid argument for either style - it is truly a matter of subjective personal preference.
1) CERT-C DCL04-C.
Because it makes more sense when you have declarations like:
int *a, *b;
For declaring multiple pointers in one line, I prefer int* a, * b; which more intuitively declares "a" as a pointer to an integer, and doesn't mix styles when likewise declaring "b." Like someone said, I wouldn't declare two different types in the same statement anyway.
When you initialize and assign a variable in one statement, e.g.
int *a = xyz;
you assign the value of xyz to a, not to *a. This makes
int* a = xyz;
a more consistent notation.
Why do most C programmers name variables like this:
int *myVariable;
rather than like this:
int* myVariable;
Both are valid. It seems to me that the asterisk is a part of the type, not a part of the variable name. Can anyone explain this logic?
They are EXACTLY equivalent.
However, in
int *myVariable, myVariable2;
It seems obvious that myVariable has type int*, while myVariable2 has type int.
In
int* myVariable, myVariable2;
it may seem obvious that both are of type int*, but that is not correct as myVariable2 has type int.
Therefore, the first programming style is more intuitive.
If you look at it another way, *myVariable is of type int, which makes some sense.
Something nobody has mentioned here so far is that this asterisk is actually the "dereference operator" in C.
*a = 10;
The line above doesn't mean I want to assign 10 to a, it means I want to assign 10 to whatever memory location a points to. And I have never seen anyone writing
* a = 10;
have you? So the dereference operator is pretty much always written without a space. This is probably to distinguish it from a multiplication broken across multiple lines:
x = a * b * c * d
* e * f * g;
Here *e would be misleading, wouldn't it?
Okay, now what does the following line actually mean:
int *a;
Most people would say:
It means that a is a pointer to an int value.
This is technically correct, most people like to see/read it that way and that is the way how modern C standards would define it (note that language C itself predates all the ANSI and ISO standards). But it's not the only way to look at it. You can also read this line as follows:
The dereferenced value of a is of type int.
So in fact the asterisk in this declaration can also be seen as a dereference operator, which also explains its placement. And that a is a pointer is not really declared at all, it's implicit by the fact, that the only thing you can actually dereference is a pointer.
The C standard only defines two meanings to the * operator:
indirection operator
multiplication operator
And indirection is just a single meaning, there is no extra meaning for declaring a pointer, there is just indirection, which is what the dereference operation does, it performs an indirect access, so also within a statement like int *a; this is an indirect access (* means indirect access) and thus the second statement above is much closer to the standard than the first one is.
Because the * in that line binds more closely to the variable than to the type:
int* varA, varB; // This is misleading
As #Lundin points out below, const adds even more subtleties to think about. You can entirely sidestep this by declaring one variable per line, which is never ambiguous:
int* varA;
int varB;
The balance between clear code and concise code is hard to strike — a dozen redundant lines of int a; isn't good either. Still, I default to one declaration per line and worry about combining code later.
I'm going to go out on a limb here and say that there is a straight answer to this question, both for variable declarations and for parameter and return types, which is that the asterisk should go next to the name: int *myVariable;. To appreciate why, look at how you declare other types of symbol in C:
int my_function(int arg); for a function;
float my_array[3] for an array.
The general pattern, referred to as declaration follows use, is that the type of a symbol is split up into the part before the name, and the parts around the name, and these parts around the name mimic the syntax you would use to get a value of the type on the left:
int a_return_value = my_function(729);
float an_element = my_array[2];
and: int copy_of_value = *myVariable;.
C++ throws a spanner in the works with references, because the syntax at the point where you use references is identical to that of value types, so you could argue that C++ takes a different approach to C. On the other hand, C++ retains the same behaviour of C in the case of pointers, so references really stand as the odd one out in this respect.
A great guru once said "Read it the way of the compiler, you must."
http://www.drdobbs.com/conversationsa-midsummer-nights-madness/184403835
Granted this was on the topic of const placement, but the same rule applies here.
The compiler reads it as:
int (*a);
not as:
(int*) a;
If you get into the habit of placing the star next to the variable, it will make your declarations easier to read. It also avoids eyesores such as:
int* a[10];
-- Edit --
To explain exactly what I mean when I say it's parsed as int (*a), that means that * binds more tightly to a than it does to int, in very much the manner that in the expression 4 + 3 * 7 3 binds more tightly to 7 than it does to 4 due to the higher precedence of *.
With apologies for the ascii art, a synopsis of the A.S.T. for parsing int *a looks roughly like this:
Declaration
/ \
/ \
Declaration- Init-
Secifiers Declarator-
| List
| |
| ...
"int" |
Declarator
/ \
/ ...
Pointer \
| Identifier
| |
"*" |
"a"
As is clearly shown, * binds more tightly to a since their common ancestor is Declarator, while you need to go all the way up the tree to Declaration to find a common ancestor that involves the int.
That's just a matter of preference.
When you read the code, distinguishing between variables and pointers is easier in the second case, but it may lead to confusion when you are putting both variables and pointers of a common type in a single line (which itself is often discouraged by project guidelines, because decreases readability).
I prefer to declare pointers with their corresponding sign next to type name, e.g.
int* pMyPointer;
People who prefer int* x; are trying to force their code into a fictional world where the type is on the left and the identifier (name) is on the right.
I say "fictional" because:
In C and C++, in the general case, the declared identifier is surrounded by the type information.
That may sound crazy, but you know it to be true. Here are some examples:
int main(int argc, char *argv[]) means "main is a function that takes an int and an array of pointers to char and returns an int." In other words, most of the type information is on the right. Some people think function declarations don't count because they're somehow "special." OK, let's try a variable.
void (*fn)(int) means fn is a pointer to a function that takes an int and returns nothing.
int a[10] declares 'a' as an array of 10 ints.
pixel bitmap[height][width].
Clearly, I've cherry-picked examples that have a lot of type info on the right to make my point. There are lots of declarations where most--if not all--of the type is on the left, like struct { int x; int y; } center.
This declaration syntax grew out of K&R's desire to have declarations reflect the usage. Reading simple declarations is intuitive, and reading more complex ones can be mastered by learning the right-left-right rule (sometimes call the spiral rule or just the right-left rule).
C is simple enough that many C programmers embrace this style and write simple declarations as int *p.
In C++, the syntax got a little more complex (with classes, references, templates, enum classes), and, as a reaction to that complexity, you'll see more effort into separating the type from the identifier in many declarations. In other words, you might see see more of int* p-style declarations if you check out a large swath of C++ code.
In either language, you can always have the type on the left side of variable declarations by (1) never declaring multiple variables in the same statement, and (2) making use of typedefs (or alias declarations, which, ironically, put the alias identifiers to the left of types). For example:
typedef int array_of_10_ints[10];
array_of_10_ints a;
A lot of the arguments in this topic are plain subjective and the argument about "the star binds to the variable name" is naive. Here's a few arguments that aren't just opinions:
The forgotten pointer type qualifiers
Formally, the "star" neither belongs to the type nor to the variable name, it is part of its own grammatical item named pointer. The formal C syntax (ISO 9899:2018) is:
(6.7) declaration:
declaration-specifiers init-declarator-listopt ;
Where declaration-specifiers contains the type (and storage), and the init-declarator-list contains the pointer and the variable name. Which we see if we dissect this declarator list syntax further:
(6.7.6) declarator:
pointeropt direct-declarator
...
(6.7.6) pointer:
* type-qualifier-listopt
* type-qualifier-listopt pointer
Where a declarator is the whole declaration, a direct-declarator is the identifier (variable name), and a pointer is the star followed by an optional type qualifier list belonging to the pointer itself.
What makes the various style arguments about "the star belongs to the variable" inconsistent, is that they have forgotten about these pointer type qualifiers. int* const x, int *const x or int*const x?
Consider int *const a, b;, what are the types of a and b? Not so obvious that "the star belongs to the variable" any longer. Rather, one would start to ponder where the const belongs to.
You can definitely make a sound argument that the star belongs to the pointer type qualifier, but not much beyond that.
The type qualifier list for the pointer can cause problems for those using the int *a style. Those who use pointers inside a typedef (which we shouldn't, very bad practice!) and think "the star belongs to the variable name" tend to write this very subtle bug:
/*** bad code, don't do this ***/
typedef int *bad_idea_t;
...
void func (const bad_idea_t *foo);
This compiles cleanly. Now you might think the code is made const correct. Not so! This code is accidentally a faked const correctness.
The type of foo is actually int*const* - the outer most pointer was made read-only, not the pointed at data. So inside this function we can do **foo = n; and it will change the variable value in the caller.
This is because in the expression const bad_idea_t *foo, the * does not belong to the variable name here! In pseudo code, this parameter declaration is to be read as const (bad_idea_t *) foo and not as (const bad_idea_t) *foo. The star belongs to the hidden pointer type in this case - the type is a pointer and a const-qualified pointer is written as *const.
But then the root of the problem in the above example is the practice of hiding pointers behind a typedef and not the * style.
Regarding declaration of multiple variables on a single line
Declaring multiple variables on a single line is widely recognized as bad practice1). CERT-C sums it up nicely as:
DCL04-C. Do not declare more than one variable per declaration
Just reading the English, then common sense agrees that a declaration should be one declaration.
And it doesn't matter if the variables are pointers or not. Declaring each variable on a single line makes the code clearer in almost every case.
So the argument about the programmer getting confused over int* a, b is bad. The root of the problem is the use of multiple declarators, not the placement of the *. Regardless of style, you should be writing this instead:
int* a; // or int *a
int b;
Another sound but subjective argument would be that given int* a the type of a is without question int* and so the star belongs with the type qualifier.
But basically my conclusion is that many of the arguments posted here are just subjective and naive. You can't really make a valid argument for either style - it is truly a matter of subjective personal preference.
1) CERT-C DCL04-C.
Because it makes more sense when you have declarations like:
int *a, *b;
For declaring multiple pointers in one line, I prefer int* a, * b; which more intuitively declares "a" as a pointer to an integer, and doesn't mix styles when likewise declaring "b." Like someone said, I wouldn't declare two different types in the same statement anyway.
When you initialize and assign a variable in one statement, e.g.
int *a = xyz;
you assign the value of xyz to a, not to *a. This makes
int* a = xyz;
a more consistent notation.
This question already has answers here:
Placement of the asterisk in pointer declarations
(14 answers)
Difference between int* p and int *p declaration [duplicate]
(3 answers)
difference between int* i and int *i
(9 answers)
Closed 4 years ago.
What is the most proper way to place asterisk? Why?
1) type* var;
2) type *var;
It does not matter as far as you are declaring only one pointer. It is usually writen like in the second example (in the code I usually read/write) but for the compiler it's the same.
The trouble can come out if you are declaring more than one pointer. For example, this is not declaring two pointer, instead it declares one pointer and one var of type type.
type* var1, var2;
You need to do instead:
type* var1, *var2;
I prefer to use the * by the var always.
Pointer is the type, and I think it makes most sense to group the type information:
int* foo;
This can lead to confusion if several variables are defined on the same line:
int* foo, bar; // foo will be int*, bar will be int
The solution to this is, never declare several variables on the same line. Something that Code Complete advocates, anyway.
Both work. I'd argue that #1 is clearer in general, but misleading in C and can lead to errors, e.g.:
type* var1, var2;
// This actually means:
type *var1;
type var2;
So I'd say that #2 is more idiomatic in C and therefore recommended, especially if you are not the only programmer working on the code (unless, of course, you all agree on a style).
As others have pointed out, both work fine, and the wrong one actually has the advantage of syntactic economy.
The way I look at it, a declaration consists of type followed by the variable.
<type> <variable>;
int ii;
int* pii;
So, if you take away the variable, what remains is the type. Which is int and int* above. The compiler treats int* as a type internally (which is pointer to an int).
C, unfortunately, does not support this syntax seamlessly. When declaring multiple variables of the same type, you should be able to do this:
<type> <variable>, <variable>, <variable>;
which you cannot with a pointer type:
int* ii1, ii2, ii3;
declares ii1 of type int* and the rest of type int. To avoid this, I make it a habit of declaring only one variable per line.
I've heard it argued that technically the * is a modifier to the variable,
and this is evidenced by the need to use * multiple times in multi variable
declarations
eg. int *p, *q, *r;
However I like to think of it as a modifier to the base type because that
is what appears in prototypes.
eg. void func(int*);
.PMCD.
PS. I know I haven't helped your problem :)
The second mode is correct. The other mode are not so clear for a novice programmer.
The form int* variable is usually discouraged
That would rather be a coder's preference.
For me, I declare pointers by:
int * var1, var2;
Wherein var1 is a pointer, and var2 is not. If you want to declare multiple pointers in a line:
int * var1, * var2;
And of course, using the other ways are valid.
Declaration semantics follow expression semantics (specifically operator precedence) and I find more complex declarations easier to read using the second style.
You can think of
int *foo;
declaring the type of the expression *foo (ie indirection operator applied to foo) to be int instead of foo being declared to be of type int *.
Whatever convention you choose, just try to be consistent.
There is no single "most proper place".
Usually it is the place the rest of the code uses.
If you're writing your own code from the beginning and can choose your own convention: choose your own convention and stick with it.
If you choose something other than type * var you will meet 'awkward' situations:
/* write these with another style */
int * var;
int const * var;
int * restrict var;
PS. It shouldn't matter, but I usually use type *var;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C, what is the correct syntax for declaring pointers?
good way to write “pointer to something” in C/C++
I am currently reading a book on C. At the moment I read about pointers.
Basically, I think that I have understood the concept. Anyway one thing puzzles me:
Sometimes the author uses
void *foo;
to create a new pointer, but sometimes it's
void* foo;
Is there a difference? Does it matter? Doesn't it? When to use what? ...?
You can have as many or as few spaces either side of the * as you like. It means exactly the same thing either way:
void*foo;
void *foo;
void* foo;
void * foo;
void * foo;
void * foo;
void * foo;
All are exactly the same thing. If you work on a project, there is usually some "coding style standard" that explains which is preferred in that project. But the compiler won't do any different based on if/where there are spaces.
They are equivalent but the former can be preferable when declaring multiple variables of non-void type in a single line
int *foo, *bar;
clearly declares two pointers, while
int* foo, bar;
declares one pointer and one int
Both are equivalent and no difference whatsoever.
int *foo, i;
But you should know the difference in declarations like above. Here only foo is of pointer type whereas i is of type int (not int*).
The two syntaxes are equivalent. The only difference is a matter of style.
There is no difference to compiler, as you probably already know.
As of the matter of style, some argue that void* ptr is better because the type name as a whole is isolated. The problem is, that's not how the language works:
int* ptr, otherptr; /* otherptr is not a pointer here */
Even if you decide against declaring multiple variables at once, the whole idea of having an isolated type name breaks for arrays and function pointers. That's why I prefer the other style:
int *ptr, *otherptr, dontDeclareTooManyThings[N];
Is there a difference?
Of course there is. (If there wasn't, you wouldn't be asking this.) The star is on one side of the whitespace in the first case, and on the other side in the other.
Does it matter?
It does. Not in terms of program logic, however - the two are parsed exactly the same way. However, it's a matter of personal preference. I generally recommend the second way, i. e. void *ptr, since the pointer qualifier (the asterisk) modifies the variable, and not the type.
When to use what?
Just explained.
Both variants are valid.
They represent different styles.
consider
char* foo, bar;
char *foo, bar;
in both cases foo is a pointer, bar is not.
also consider (readability)
char* foo() {
// return something
}