Almir
Almir

Reputation: 59

C++ declaring multiple variables in the same line

I know that declaring variables like this int a = 10, b = 15, c = 20 is possible and it's ok, but is it possible in any program in c++ programming language, to declare variables like this int a, b, c = 10, 15, 20 where a need to be 10, b need to be 15 and c to be 20.

Is this possible and is it right way to declare variables like this in c++?

EDIT: Is it possible with the overloading operator =?

Upvotes: 5

Views: 10450

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

The compiler will issue an error for such declarations

int a, b, c = 10, 15, 20; 

The only idea that comes to my head is the following :)

int a, b, c = ( a = 10, b = 15, 20 ); 

Or you could make these names data members of a structure

struct { int a, b, c; } s = { 10, 20, 30 };

EDIT: Is it possible with the overloading operator =?

There is not used the copy asssignment operator. It is a declaration. The copy assignment operator is used with objects that are already defined.:)

Upvotes: 8

Jarod42
Jarod42

Reputation: 217810

int a, b, c = 10, 15, 20;

is not valid, (and even if it is it would probably initialize c to 20 (with comma operator) and let a and b uninitialized.

using c-array/std::array/std::vector may be an option:

int carray[3] = {10, 15, 20};
std::array<int, 3> a = {10, 15, 20};
std::vector<int> v = {10, 15, 20};

now we have carray[0] == a[0] && a[0] == v[0] && v[0] == 10

Upvotes: 1

Related Questions