vik-y
7/5/2017 - 7:35 AM

Static variables, functions, references and everything , they behave in a very complex. This gist tries to experiment with those concepts

Static variables, functions, references and everything , they behave in a very complex. This gist tries to experiment with those concepts

#include<iostream>
using namespace std;

int &fun()
{
	static int x = 10;
	return x;
}
int main()
{
	fun(); // Will initialize the static integer inside fun()
  // A static variable once defined stays in memory till the end of the program
  // Only thing is that its scope stays inside the function. 
  // But if we can copy its reference then we can use it anywhere
	cout << fun() << endl; // Prints 10 
	int &x = fun(); // Gets reference to the static variable
	x = 100; // Modifies the reference. This should modify the static variable too
	cout << fun() << endl; // Verifying if static variable was modified or not 
  // It outputs 100 and that means we were right.
	return 0;
}

// This function will throw complation error because int x inside this function 
// gets removed as soon as the function call is completed and hence returning
// a reference of x doesn't make sense. 
int &fun2(){
  int x = 10;
  return x;
}

/*
OUTPUT
10
100
*/
#include<iostream>
using namespace std;
 
int main()
{
   int *ptr = NULL;
   int &ref = *ptr; // We are initializing the reference. 
   cout << ref;
}

// At run time ref will be referencing to NULL and hence it will
// give a segmentation fault