What happens when I declare say multiple variables on a single line? e.g.
int x, y, z;
All are ints. The question is what are y and z in the following statement?
int* x, y, z;
Are they all int pointers?
What happens when I declare say multiple variables on a single line? e.g.
int x, y, z;
All are ints. The question is what are y and z in the following statement?
int* x, y, z;
Are they all int pointers?
Only x is an int pointer. Y and Z will be just int. If you want three pointers:
In your first sentence:
They are all
int
s.However, in the second one:
Only
x
is a pointer toint
.y
andz
are plainint
s.If you want them all to be pointers to
int
s you need to do:It is important to know that, in C, declaration mimics usage. The * unary operator is right associative in C. So, for example in
int *x
x is of the type pointer to an int (or int-star) and inint x
, x is of type int.As others have also mentioned, in
int* x, y, z;
the C compiler declares x as an int-star and, y and z as integer.Only
x
is a pointer to int;y
andz
are regular ints.This is one aspect of C declaration syntax that trips some people up. C uses the concept of a declarator, which introduces the name of the thing being declared along with additional type information not provided by the type specifier. In the declaration
the declarators are
*x
,y
, andz
(it's an accident of C syntax that you can write eitherint* x
orint *x
, and this question is one of several reasons why I recommend using the second style). The int-ness ofx
,y
, andz
is specified by the type specifierint
, while the pointer-ness ofx
is specified by the declarator*x
(IOW, the expression*x
has typeint
).If you want all three objects to be pointers, you have two choices. You can either declare them as pointers explicitly:
or you can create a typedef for an int pointer:
Just remember that when declaring a pointer, the
*
is part of the variable name, not the type.