Question:
C++ Local and Global variables difference?
Robert
2012-04-22 08:39:32 UTC
In terms of accessibility, local variables can only be accessed in the function it is created in; global variables can be accessed by any function in the program. Am I right here?

What about initial value and life span? These 2 I cant understand.
Four answers:
Rohit
2012-04-22 11:42:35 UTC
Hi...



You're right about the accessibility!



LIFE SPAN

Life span is the same as accessibility. Global variables are alive until the program ends. Local variables are alive only until the function execution ends.



INITIAL VALUES

Global variables are initialized with value 0 (Zero).

Local variables are initialized with Garbage Values i.e, Random Values.



Hope it helps...
stigsell
2016-10-22 10:26:39 UTC
international ability you should use it in any journey, community ability you are able to basically use it contained in the shape the position that's declared. get together, C++: #comprise iostream employing namespace std; bool x; //international Boolean variable, may be used everywhere void attempt() { //x may be used the following, yet y won't be able to } int significant(); { int y; //community y integer, can basically be used in this journey { VB6: Dim x as string 'international x variable, because that's outdoors the activities deepest Sub Command1_Click() Dim y as integer 'community y variable, because that's interior an journey end Sub
NextGenCplusplus
2012-04-22 10:12:02 UTC
Yes, you're right.



The initial value and life span differ in this way:

-Both variables are initialized the same way. (ex. int y = 5;).

-The span of the variables goes like this: A local variable is only active while you're in the function it was initialized in. Global Variables are active throughout the whole program.
nitya
2012-04-22 08:55:51 UTC
it is very simple. the local variables are the ones whose scope is limited to the function in which it is defined. whereas the global variables are recognized everywhere in the program.

also the local variables have higher priority than the global variables. this means that if a variable say x is defined globally and is assigned a value say 5, but it is redefined in a particular function and assigned the value 3(only for that function) then the compiler will give higher priority to x=3. also both values are stored under name x but not over-written.

hope that helps!


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...