Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

variables - C multiple single line declarations

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...