jeudi 13 août 2015

Why the variables defined inside a for loop only exist inside of it?

I was reading C++ Primer from Stanley B. Lippman and at the part of flow control it shows an example of a for-loop like this one:

#include <iostream>

int main(void){
    int sum=0;
    for (int val=1; val <= 10; val++)
        sum +=val;
    std::cout << sum << std::endl; 
    return 0;

}

If I try std::cout << val; outside of the for-loop, the IDE gives me an erro. But I want to understand why it happens and how it is different from this code:

#include <iostream>

int main(void){
    int sum=0;
    int val;
    for ( val=1; val <= 10; val++)
        sum +=val;
    std::cout << sum << std::endl;
    std::cout << val; 
    return 0;

}

Where I can actually print the val value without any problem.

Does it have something to do with local variable considering the for-loop a function that we are using inside of the main?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire