





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The concept of variable scope in c++ programming. It covers file scope, block scope, and the importance of declaring variables before or after functions. The document also includes an example to illustrate the different memory locations and values of variables with the same name but different scopes.
Typology: Slides
1 / 9
This page cannot be seen from the preview
Don't miss anything!






program where that variable name is defined.
which define a function (such as " void main ( ) " ) has file scope. That is, its name, its designated memory location, and any value assigned to it will be known throughout the main function and any other function (subprogram) in the same file of source code.
#include <stdio.h> int main ( ) { int x = 3 ; /* Now "x" known, program compiles */ FILE *fptr ; fptr = fopen ("scope.dat", "w") ; fprintf (fptr, ”before if block, x=%d\n", x) ; if ( x == 3 ) { float x = 4.5 ; fprintf (fptr, "inside if block, x=%f\n", x) ; } fprintf (fptr, "after if block, x=%d\n", x) ; }
the previous slide, x is known throughout the program, but the x inside the if block of statements has a different data type and has a different value than the one outside the block.
different memory locations, and thus we have two completely different variables with the same name. (Confusing, eh?)