Question

int main(void) {
    int i = 2, k = 3, a;
    i++;
    ++k;
    {
        int i = 0;
        i = k++;
        printf("%d,%d,", i, k);
    }
    printf("%d,%d", i, k);
    getchar();
    return 0;
}

Why this code produces output "4,5,3,5" why not "4,5,4,5"? Why when I trace code by f7 key c++ then it goes first printf then second printf(). So according to this value of variable must remain 4, then why it give value of i variable 3 in second printf() function?

Was it helpful?

Solution

Second printf doesn't "see" that i declared as int i =0;, because that i is in another scope created by your curly braces.

So, the second printf takes the first i, which was declared (and defined) as int i =2 and in the next line incremented to 3 with i++.

By the way, code indentation is your friend (and ours too:).

OTHER TIPS

Because curly braces delimits blocks, and in C variables are local to blocks.

So the second i is local to the inner block and different to the first which is local to the function main.

Take a look to this commented version of your code:

main(){
  int i =2,k=3,a;
  i++; // i = 3
  ++k; // k = 4
  {
    int i =0; // Lets call it i', then i' = 0 (it is different to i)
    i=k++; // i' = k = 4, then increment k so k = 5
    printf("%d,%d,",i,k); // Prints i', k: "4,5,"
  }
  printf("%d,%d",i,k); // Prints i, k: "3,5"
  getch();
}

Curly braces in C define block scope. So the i in the block delimited by the curly braces is different from the one outside it. I am tweaking your code a little bit and adding comments where helpful.

// main should return int. void type should be explicit in the parameter list

int main(void) {  
    int i = 2, k = 3, a;
    i++;   // i is 3 
    ++k;   // k is 4
    {                            // block scope starts
        int i = 0;               // not the same as the previous i
        i = k++;                 // block level i is 4 as k is 4
        printf("%d, %d", i, k);  // prints 4, 5 
    }                            // block scope ends
    printf("%d, %d", i, k);      // prints 3, 5
    getchar();                   // getch is nonstandard. use getchar instead
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top