1

Note: This is coming from a beginner.

Why does the first one outputs 333 and the second one 345 ?

In the second code does it skips over the declaration? I mean it should initialise the "j" variable again like in the first one.

int main() {
    static int j =12;
    for(int i=0; i<=2; i++) {
        j = 2;
        j += 1;
        std::cout<<j;
    }
    return 0;
}

int main() {
    
    for(int i=0; i<=2; i++) {
        static int j = 2;
        j += 1;
        std::cout<<j;
    }
    return 0;
}
2
  • 2
    First question: What's your understanding of what static variables are?
    – tadman
    Commented Mar 28, 2021 at 18:22
  • "it should initialise the 'j' variable again" -- why?
    – JaMiT
    Commented Mar 28, 2021 at 23:04

1 Answer 1

2

static variables are only initialized once (when first used). After that, it behaves as if it is declared somewhere else (I mean, the initialization is ignored). In the second main, the initialization static int j = 2; is executed only the first time, after that, you are incrementing it sequentially (i.e. 2,3,4...) In the first loop, you set it's value on each iteration, which is not the same as initialization, so it can be run multiple times.

Not the answer you're looking for? Browse other questions tagged or ask your own question.