[Solved] Result of a program in C++ including global and local variables


The “parts in the program” where a variable is valid is called the variable scope.
C++ is flexible and allows for variable overriding.

here is some explanations, but ultimately you have to play with it yourself to find out.

this is best shown in example:

#include <iostream>
using namespace std;

int num1(1); //this is global scope
int num2(2); //so is this
//global variables are available inside all functions including main


int foo1(int val) {  //num1 and num2 are available here
  val = val + 1;  //val is a parameter passed by value. it is just a copy
  //what you do to val here will not stick to the variable that was passed in
  return val;
}

int foo2(int& val) {
  val = val + 1;   //val is a parameter passed by reference, what you do to it here will stick
  num1 = num2 + 1; // global variables are available to be manipulated
 // (changes will stick because there is no copy in function)

  return val - 1;   //(val-1) is a temporary value (rvalue), it does not affect value of val;
}

//val is not available here, because it is only a function parameter valid in the bodies of foo1,foo2 and foo3.

int foo3(int& val) { //val is an integer again passed by reference, means changing it will change the variable that was sent to this function.
  int num2(2); //this is a variable declared in the scope of this function, 
 //it is only available in this function, when this function returns
 //then num2 is destroyed.

 //this is generally not considered good practice, because you are masking 
 //a global variable, from now on, num2 refers to the local copy
 //if you want the global num2 you have to use ::num2 

  num2 = num2 + 1; //whatever we do to num2 is for the local copy only
 //becuase we overrode the name.(usually bad idea)

  return foo1(3*num1) + foo2(val) ; 
}

int main() {
 //global num1 is available here 

  int num1(3); //here is another example of overriding a global variable. 

  //at this point num1 no longer refers to the global variable,
  // instead it refers to the local variable declared in main. 
  //if you want global variable num1 you should use ::num1

  cout << "Resultat 1: " << foo3(num1) << endl;  //passes the local variable num1 by reference. it will take the name "value" inside foo3
  cout << "Resultat 2: " << num1 << endl;
  cout << "Resultat 3: " << num2 << endl;
}

There is another very important lesson to be learned here: pass by value and pass by reference semantics.
a function that takes a parameter by value only receives a copy. subsequent changes to that variable inside the function body will not affect the parameter that was passed in.

in contrast, a function that takes a parameter by reference, will receive a “reference to the variable” which allows it to modify the variable directly.

3

solved Result of a program in C++ including global and local variables