In: Computer Science
What is the output from the following program? Explain your results.
file:///Users/brianabernal/Downloads/Question%201.pdf
int val = 20;
int func1()
{
int val = 5;
return val;
}
int func2()
{
return val;
}
int main()
{
// (1)
cout << func1() << endl;
// (2)
cout << func2() << endl;
}
Whatever is needed to answer this question is already in the code given so I'm assuming the pdf file directory that you hvae provided is not relevant here.
The output of the code is as given below:
The function func1() gives output as 5 and func(2) as 20 because of a simple concept that c++ uses called "scope of a variable". Here we see that int val = 20; in this a variable named val is declared globally i.e. its existence is for the entire code and wherever it is used, its value will be retrieved from the stack record created and that's why when func2() calls it for printing, it is recognized by the compiler and not the variable val declared in func1() because that val is separately created in the stack memory and its scope is only within func1().