APS105 L11 - Scope

#APS105 Slides Lecture Link to web notes
The scope is a part of the program where you can use a variable.
You can use a variable declaration between the { } in a function.
Variables exist within a function, and aren't "global".

For loop creates an "inner scope".

Example:

int main(void) {
	int i = 42;
	for (int j = 0; j < 1; ++j) {
		printf("j: %d\n", j); // j is only useable within the body of the for loop
	}
	return 0;
}

Outside of the for loop in the above example, j is out of scope.

Shadowing a variable with the same name

If you have multiple declarations of the same variable, C will use the most recent declaration.

Example: i in the for () is prioritized over the initial declaration of i = 42 when the code in the for loop is run.

#include <stdio.h>
int main(void) {
int i = 42;
for (int i = 0; i < 1; ++i) {
printf("i: %d\n", i);
}
printf("%d\n", i);
return 0;
}

Creating a new inner scope

You can do this by using a set of curly braces.

"Typically, you wouldn't really do that, but you're allowed to." - Eyolfson

Example:

#include <stdio.h>
int main(void) {
	int i = 42;
	{
		int i = 0; // this is a new scope, so previous i is overwritten (returns 0)
		printf("%d\n", i);
	}
	printf("%d\n", i); // in outer scope, i is not overwritten (returns 42)
	return 0;
}

Important Eyolfson interjection!!! (1)
When you use scanf() with a character value, make sure to put a space before the %c! This makes it so that it ignores the user's inputted spaces.

Important Eyolfson interjection!!! (2)
NEVER put a space AFTER %c in scanf.