Created
July 5, 2017 07:35
-
-
Save vik-y/42797f27de3fb9b3fa32e6f5384323e9 to your computer and use it in GitHub Desktop.
Static variables, functions, references and everything , they behave in a very complex. This gist tries to experiment with those concepts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment