33

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?

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
ruralcoder
  • 1,000
  • 1
  • 10
  • 18

4 Answers4

65

Only x is a pointer to int; y and z 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

int* x, y, z;

the declarators are *x, y, and z (it's an accident of C syntax that you can write either int* x or int *x, and this question is one of several reasons why I recommend using the second style). The int-ness of x, y, and z is specified by the type specifier int, while the pointer-ness of x is specified by the declarator *x (IOW, the expression *x has type int).

If you want all three objects to be pointers, you have two choices. You can either declare them as pointers explicitly:

int *x, *y, *z;

or you can create a typedef for an int pointer:

typedef int *iptr;
iptr x, y, z;

Just remember that when declaring a pointer, the * is part of the variable name, not the type.

John Bode
  • 119,563
  • 19
  • 122
  • 198
  • 1
    Truly a complete answer and to that of the underlying question of whether the * is for the type or the variable. – ruralcoder Jul 14 '10 at 14:58
9

In your first sentence:

int x, y, z;

They are all ints.

However, in the second one:

int* x, y, z;

Only x is a pointer to int. y and z are plain ints.

If you want them all to be pointers to ints you need to do:

int *x, *y, *z;
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • 3
    This is one reason the spacing `int* foo;` is really misguided. In this question's example, it makes it look like the 3 variables are all of type "`int*`". I would say this spacing is almost as offensive as `a+b * c`. – R.. GitHub STOP HELPING ICE Jul 14 '10 at 14:59
8

Only x is an int pointer. Y and Z will be just int. If you want three pointers:

int * x, * y, * z;
Macmade
  • 52,708
  • 13
  • 106
  • 123
4

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 in int 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.

hyde
  • 2,525
  • 4
  • 27
  • 49