Search code examples
c++initializationdeclarationassignment-operator

Initialize several variables separated by comma ','


Using C++14, if I want to declare and initialize two integers on the same instruction (using comma separator):

int i,j = 0;
std::cout << i << "," << j << std::endl;

Then only the rightest variable (j) is initialized correctly. Indeed, the compiler outputs a warning message:

warning: 'i' is used uninitialized in this function [-Wuninitialized]

Of course the solution is to repeat it on each variable

int i=0, j=0;

But the question is:

Is there a way to correctly initialize several variables with only one assignment operator ?


Solution

  • Sadly not; it's a quirk of the grammar.

    int i(0), j(0);
    

    is an alternative, valid from C++98. If you don't like repeating the literal 0, then you could, for that special case at least, write from C++11 onwards

    int i{}, j{};