Counting Cards - need help understanding control flow

Hi there,

I have a question about the Counting Cards Code. I am not looking for the solution - I have that - but rather would like to understand why the solution works the way it does.

Specifically, my question is: once I have executed a function run (let’s say cc(2)), why is the variable count now globally set to 1, so that next time I run the function (let’s say cc(3)), it starts at 1 (and not 0)? I find this rather confusing and would expect the variable to be initialized at 0 every time I execute code.

Would really appreciate an explanation. Thank you!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36.

count is a global variable, so it gets updated “outside” the function, so to speak. Global variables that keep state are very much frowned upon in real-world code, but the lessons are trying to keep things simple, even at the cost of some correctness.

Thank you! I think my mistake in thinking was that I assumed that the program runs each time it executes the function and then starts back up again and executes the next function. Once I started to see the line cc(2); cc(3); cc(7); cc('K'); cc('A'); as a sequence which finishes with the last call to the cc-function, it made sense.

Sometimes it’s just going back to the basics and keeping track of where we’re at at each point in time when code gets executed. :grinning: