Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare and define multiple variables in one line using C++?

Tags:

c++

People also ask

How do you define multiple variables in one line?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.

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 multiple variables?

But there are actually shorter ways to declare multiple variables using JavaScript. First, you can use only one variable keyword (var, let, or const) and declare the variable names and values separated by commas.

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.


int column = 0, row = 0, index = 0;

When you declare:

int column, row, index = 0;

Only index is set to zero.

However you can do the following:

int column, row, index;
column = index = row = 0;

But personally I prefer the following which has been pointed out.
It's a more readable form in my view.

int column = 0, row = 0, index = 0;

or

int column = 0;
int row = 0;
int index = 0;

As @Josh said, the correct answer is:

int column = 0,
    row = 0,
    index = 0;

You'll need to watch out for the same thing with pointers. This:

int* a, b, c;

Is equivalent to:

int *a;
int b;
int c;

If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.

To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;.