2

This is my code

#include <iostream>

int main()
{
    int j = 1;
    for (int i=0, j=1; i<10; i++)
    {
        std::cout << j << std::endl;
        j++;
    }
    std::cout << j << std::endl;

    return 0;
}

This is my output:

2
3
4
5
6
7
8
9
10
11
1

I just want to know why the value of j does not change out

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Grey
  • 41
  • 5

1 Answers1

5

You have two variables j:

    int j = 1; // 1st "j" here
    for (int i=0, j=1; i<10; i++) // 2nd "j" here

You are modifying 2nd j in the loop and printing 1st j after the loop.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • It's quite possible OP did not intend to create a second var. In this case, they could use (the not so nice) `for (int i=(j=1,0); i<10; i++)` – Jeffrey Apr 27 '21 at 15:05
  • 2
    @Jeffrey I think it should simply be `for (int i=0; i<10; i++)` in this case because `j` is already initialized to `1` at the declaration. – MikeCAT Apr 27 '21 at 15:07
  • 1
    yeah. The mystery really is why specify `j=1` at that exact location – Jeffrey Apr 27 '21 at 15:09