Sunday, June 30, 2013

C++(beginner) local and global variables.

The local variable can be used only in the place they have been declared , If you try to use them outside the place they have been declared you will get a compiler error.

The black bordered rectangle is the place for writing global variables. NOTE you can't use variable before their declaration no matter its local or global.
As we know the main part of our code is a function also (void main or int main) and the variables declared in main can't be used in other places. The variable I created on the 4th line int global_variable1 and int global_variable2 can be used everywhere in code, in any function but the variable I created in main function int local_variable1 and int local_variable2 can be used only in main function. NOTE if you declare a global variable and another variable in main with the same name, every time you call that variable you will get the value of the one you declared in main.
There are some limits , suppose you want to declare an array of integers with the lenght of 1000000 (1 million). If you try to do that in main function , after running your program you will get an error. For example this one.

You may also get the "error reporting " window.

No comments:

Post a Comment