-2

The following code prints AA:

#include <stdio.h>
int main()
{
    for(int i;i;i--)
        printf("A");
    return 0;
}

Why the initial value of variable i is 2, and not some garbage value?

Is the lifetime of variable i static or automatic?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
user300046
  • 103
  • 1
  • 8

2 Answers2

2

Apparently the variable i is not initialized. This means that the behavior of the implementation is undefined. And value of i is garbage value only. Here it is 2.

VatsalSura
  • 926
  • 1
  • 11
  • 27
Codor
  • 17,447
  • 9
  • 29
  • 56
1

The scope of the variable i is the entire for-statement (including its body). It has the automatic storage duration and will be destroyed after exiting the loop. You may not declare it as having the static storage duration as for example

for(static int i;i;i--)
    printf("A");

As the variable i was not initialized it has an indetermined value that can be a trap value.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335