Skip to content

Instantly share code, notes, and snippets.

@brianisbrilliant
Created March 17, 2021 15:46
Show Gist options
  • Save brianisbrilliant/141c4847a22d77fd09a6247f254adcc9 to your computer and use it in GitHub Desktop.
Save brianisbrilliant/141c4847a22d77fd09a6247f254adcc9 to your computer and use it in GitHub Desktop.

Sure I can! The textbook definition of variable scope is "variables only exist in the code block they were created in". and by code block, that's anything in between { curly braces }.

so, like this:

int main() {
    if(true) {
        string kid = "Billy";  // this only exists in the if statement's code block
    }

    cout << kid;  // this throws an error because the variable "kid" does not exist here.
}

and the metaphor works like this: if I said "Give this toy to the kid" and there was only one kid in the room, you would know who to give it to, right? But if you were outside the room, how could you know if there was a kid in there? You wouldn't, and you wouldn't be able to interact with that kid, because they are in another room. Variable scope is just like that.

There is one other case where you have nested variable scope, with two variables with the same name.

int main() {
    string kid = "Billy"
    if(true) {
        string kid = "Bob"
        cout << kid;   // this says "bob" because we "overwrote" the kid variable temporarily.
    }
    cout << kid;   // this says "billy" because the "bob" kid variable doesn't exist anymore.
}

In this scenario there is a kid sitting next to you on the couch and a kid further away, on the other side of the room. if I am also sitting next to you on the couch and I say "Give this toy to the kid", you would assume that I mean the kid next to you. If I weren't on the couch, you may assume I meant the kid across the room, because I am not in the same space as you. But computers can't really handle ambiguity like "which kid do you mean?" so we build this rule about variable scope, where variables cease to exist once the code block ends.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment