80 likes | 177 Views
Today’s Material. scope of variables temporary variables compound statements (blocks) and variables. printed in the for loop. scope of n. printed at the end. Scope of a Variable. " Scope of a variable " is the section of code where the variable can be accessed
E N D
Today’s Material • scope of variables • temporary variables • compound statements (blocks) and variables
printed in the for loop scope of n printed at the end Scope of a Variable • "Scope of a variable" is the section of code where the variable can be accessed • That is, its value can be read/modified. int main(){ int n; for(n = 0; n < 5; n++) { printf("%d + ", n); } printf("%d = %d\n", n, n * (n + 1) / 2); return 0; } 0 + 1 + 2 + 3 + 4 + 5 = 15
Scope of sum Scope of n Scope of a Variable • We can define new variables at the beginning of ANYcode block • In portions of the code enclosed within '{' and '}‘ • Scope of those variables will only be the code block in which they are declared + 0 = 0 + 1 = 1 + 2 = 3 + 3 = 6 + 4 = 10 int main(){ int n; for(n = 0; n < 5; n++) { int sum = n * (n + 1) / 2; printf(" + %d = %d\n", n, sum); } return 0; }
Temporary Variables • In the previous program, sum is a temporary variable. • The for loop executes five times, for n = 0, 1, 2, 3, and 4. • Each time, a new sum variable is created, used to hold the value of a formula, printed on the screen, and thrown away at the end.
Scope of x2 Scope of x6 Scope of x Temporary Variable Examples • This sample code uses a compound statement just to be able to create temporary variables: int main(){ double x = 0.12; printf("x = %.6lf\n", x); { double x2 = x * x; double x6 = x2 * x2 * x2; printf("x^2 = %.6lf\n", x2); printf("x^6 = %.6lf\n", x6); } return 0; } x = 0.120000 x^2 = 0.014400 x^6 = 0.000003
Overlapping Scopes; Occlusion • Two variables by the same name can be used, but this is not a good idea. • The more local/temporary variable will occlude the other variable. • Only the local variable will be accessible. • The other variable can't be reached.
Scope of first n Scope of temporary n Occluded Variable Example int main() { int n = 573; printf("n = %d\n", n); { int n = -1234; printf("n = %d\n", n); } printf("n = %d\n", n); return 0; } • These are two different variables • We can't access the first n • within the compound statement n = 573 n = -1234 n = 573
Multiple Scopes and Occluded Variable Example int main() { double n = 1.99; printf("n = %.4lf\n", n); { int n = 573; printf("n = %d\n", n); } { int n = -1234; printf("n = %d\n", n); } printf("n = %.4lf\n", n); return 0; } There are three different variables n = 1.9900 n = 573 n = -1234 n = 1.9900