Search code examples
c++c++11initialization

C++ variable list Initialization


So here are piece of 2 code

#1

int i=0, j=0;

for (i=0,j=0; i<=5; i++, j++)
    {
        cout<<i<<"  "<<j<<endl;
    }

#2

int i{0}, j{0};

for (i{0},j{0}; i<=5; i++, j++)
    {
        cout<<i<<"  "<<j<<endl;
    }

Build Messages

1st code allows me to replace the value inside for loop that was stored in i and j. But in the code #2 (in which I used c++11 list initialization) it shows some errors. But this works :

int i{0}, j{0};

for (i,j; i<=5; i++, j++)
    {
        cout<<i<<"  "<<j<<endl;
    }

Why can't I replace them inside loop? What is the correct way for #2 and how should I Proceed?


Solution

  • List initialization, as the name suggests, is for the initialization of a variable. Initialization can only happen once, initially. You can assign to a variable, but list initialization is not for assignment (and yes, I know some types do allow assignment from braced-init-lists, but int isn't one of them).

    So the correct way to do #2 is to not do it.