Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 836
ruralcoder Avatar asked Jul 14 '10 13:07

ruralcoder


People also ask

Can you declare multiple variables in one line in C?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

Can I declare multiple variables in single line?

Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable are handled correctly.

Can you declare a variable multiple times in C?

Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.

What is multiple declaration error in C?

E2238 Multiple declaration for 'identifier' (C++)An identifier was improperly declared more than once. This error might be caused by conflicting declarations, such as: int a; double a; A function declared in two different ways. A label repeated in the same function.


1 Answers

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.

like image 185
John Bode Avatar answered Sep 17 '22 14:09

John Bode