Defining global variable as a local variable in c - c

I have tried something like this :
int globalvar=10;
void print ()
{
printf("%d \n",globalvar);
}
int main(){
int globalvar=5;
printf("%d \n",globalvar);
print ();
while (1);
return 0;
}
and then the output went like this
5
10
I have concluded that C has created a LOCAL instance of "globalvar" inside main and it's initialized with the value 10 which is printed out by printf.
I am okay with that point but I have got confused with some new points :
globalvar which is initialized before the main is supposed to have the scope allover the program with its same memory location in DS , what does it happen in that case where there's a variable with its same name defined locally in a function ( ex: main ), ?
second question is related to the linker : How does the linker deal with these two variables of the same names so it executes in the way it executed?
PS : After downvoting the question , I want to say that I really searched the issue and I didn't find a similar question and I thought that asking a question like this will be useful to others.
I wish I am not misunderstod

I have concluded that C has created a LOCAL instance of "globalvar" inside main and it's initialized with the value 10 which is printed out by printf.
No, you created a local variable called globalvar initialized to 5. You then use it in printf. print() has no idea at all about that variable, and uses the global one set to 10.
what does it happen in that case where there's a variable with its same name defined locally in a function ( ex: main ), ?
Local variables take precedence. If you want to use the global variable, you should name your local variable something different so it does not conflict.
This is all within the same file, so the linker does not deal with the interplay of these two variables at all.

First the printf in main is called. It outputs 5 - the value of the local variable defined in main.
Then print is called, and it calls printf to output the value of global variable.
Linker has nothing to worry about - it does not deal with local variables at all, they cannot be accessed by name from outside of the function they are declared in, so the name of a local variable normally is not even visible to the linker.

Your local variable overrides your global variable inside a function. And scope of local variable will end as soon the scope of your function over. So if you call another function which don't have a local variable in same name, you can see the global variable value.
Linker don't have any role in this feature. This feature is managed by the scope of the variable in a program.

Related

How global and local with same static variable names stored in C internally memory?

#include<stdio.h>
static int a=5;
main()
{
static int a=15;
printf("%d\n",a);
}
So, how are both variables a stored in internal memory?
How are global and local variables with the same variable names stored internally in memory?
#include<stdio.h>
static int a=5;
int main()
{
printf("%p\n",(void *)&a);
static int a=15;
printf("%p\n",(void *)&a);
return 0;
}
Output for the upper program is
0x564e6b67a030
0x564e6b67a034
So you can see that both are stored in different addresses. As one is a global variable and other is local.
The names are only of interest to the human reader and the compiler/linker translating that code to machine executable code. The final object code resolves these to addresses and the names no longer exist.
The compiler distinguishes these the same way you do - by scope; when two identical symbols in the same namespace are in scope simultaneously, the symbol with the most restrictive scope is visible (i.e. may be accessed via the name).
For symbols with external linkage (in your example there are none other then main), the compiler retains the symbol name in order to resolve links between separately compiled modules. In the fully linked executable the symbol names cease to exist (except in debug build symbol meta-data).
The thing is the scope don't let them mess up. The first one has file scope and the other has block scope. (They are different variables - they are stored in separate memories.)
When you use it in the block - compiler checks whether this reference is resolved by anything in the same block. It gets one. And done.
And in case it is in some other function - if it doesn't find anything named a - the search ends in file scope where it finds the name a. That is where the story ends.
Both being static their storage duration is same. They live till the program exists. But their scope is different. If the scope was same too - compiler would have shown you error message.
Here if you compile with -Wshadow option - it will warn you about shadowing a variable. You shadowed the outer a with the inner on that block. That's it.
The facetious answer is that they are stored in different places.
Remember that the names of variables do not (normally) form part of the compiled program, so the compiler just follows the normal rules of variable shadowing. So in your case your print function (that's not a standard C function by the way - did you mean printf?) outputs the a declared in main. The fact that you've used the same name will not bother the compiler at all.
Finally C provides no way of accessing the global scoped a once the other declaration is encountered in main as it's static. (It is wasn't static you could use extern.) See How can I access a shadowed global variable in C?

Are same static variables used for each recursive call to a function? [duplicate]

This question already has answers here:
Static variable inside of a function in C
(14 answers)
Closed 8 years ago.
As per my understanding, each called function has some memory allocated to it in the program stack, and this holds true even if the same function calls itself recursively (i.e, each invocation has it's own memory in program stack). Please answer the following two questions arising from my program below:
If a variable is declared static in a function, will the same variable/same copy be used for all recursive calls of that function?
If the variable is not declared static (e.g, simply "int x"), will each recursive call to the function have its own copy of that variable? If yes, is that the way it normally happens when a function is called from other function, including the recursive calls?
#include<stdio.h>
#include<stdlib.h>
int main()
{
static int x=0;
x++;
printf("Team %d\n",x);
if(x<10)
main();
else
exit;
}
Output:
Team 1
Team 2
Team 3
Team 4
Team 5
Team 6
Team 7
Team 8
Team 9
Team 10
If a variable is declared static in a function, will the same
variable/same copy be used for all recursive calls of that function?
Yes, as your code sample shows
If the variable is not declared static (e.g, simply "int x"), will
each recursive call to the function have its own copy of that
variable? If yes, is that the way it normally happens when a function
is called from other function, including the recursive calls?
Yes, each call will have it's own stack frame with a copy of each local variable. This is what happens for every function call, whether they are recursive or not. And yes, this very principle allows, among other things, recursion.
Static variables live the life of the program, there is only one copy
Locals (Autos) get a new copy on the stack each function call.
Parameters passed by value get a new copy as well.
Parameters passed by reference (pointer) point to the copy that's passed to them. Therefore if it's a local in a recursive execution, it might be a unique copy; but usually it's a reference to a variable that called the function before the recursion started, therefore, the same copy.
It's better to do the functionality you're doing by passing a pointer to a variable, you have more control over subsequent instances of recursion.
Your understanding fairly accurate.
static means there is one version of the variable. Each time a function is called that contains a static variable the variable will have the last value assigned to it. A global variable can also be marked static which means its scope is limited to that file.
When a function is called its local variables are placed on the call stack. This stack is pushed for each function call and then popped when each function exists. A recursive call just keeps pushing a new copy of the same function onto the stack.

monitoring static variable inside a function in eclipse CDT

In c, when a variable is defined static within a function, the value of the variable is retained all the time. So probably, it's stored in the bss or data section.
However, in Eclipse CDT debugging, when trying to inspect this variable, typing the variable name in the expression pane only display the variable when the stack frame is in the function, like local variable.
Is it a bug in eclipse ?
Edit:
In IAR Embedded workbench, static variables in functions can be watched outside the function in debugging, so it's possible.
While the variable is, in fact, stored in the heap... it remains that the scope of the variable is local to the function. It's value has no meaning outside of that function and it should never change when outside of the function... unless you're passing pointers to it around, in which case you can view it in any function that has access to that pointer.
So... no... it's not a bug.
You need to qualify the static variable with the function in order to determine the scope, e.g. foo::myvar if myvar is defined in function foo.

Static functions and variables in C

I know what is the purpose of using static variables in an object oriented language, still, I don't understand what is the meaning of using the "static" keyword in C.
Can someone explain it to me?
On a function or global variable, static makes the function or global variable local to that file; other files cannot access that function or global variable by that name (but they can access it if you give a pointer to it away).
On a local variable, it makes it act as if it was a global variable, but is only accessible within that function (unless, again, you give a pointer to it away).
The value that a static variable has upon leaving a function is the same value that variable will have the next time the function is called.
A static function can be called only from within the same file that the function appears.

Strange error while executing a C code in MSVC 2005

I am facing following quirky error.
I have a workspace in MSVS2005 of all C code. I have declared a global variable in one C file.(file1.c) This file has function main() in which, I initilaize the value of that variable = 0.In other C file(file2.c). From main there is a function call to a function(func1 in file2.c) which sets the value of this global variable to 1. In file2.c I have declared the global variable as "extern .." and accessed it. But what i noticed is that in the main function moment the code execution enter the function func2, I see in the watch window that the address of that global variable itself is changed to a totally different address(In watch window I am watching &variable). As a result, when the value of that variable is set to 1, it writes the value 1 to altogether different memory address itself. So when later I use this variable to check in a if condition(if variable == 1), it still shows value of 0 and does not go satisfy the if condition and does not take that code path , where it was expected to have taken that path.
Workaround:
I declared that variable in one of my exisitng global structure, and then accessed this variable for doing the same operations; the code works as expected.
So what could be the explanation for the error which is causing the address of the global variable to be changed if its declared as a global in some C file? It does not matter in which *.c file i declare it and which file I access it using "extern" , the result is same global variable address change and subsequent errorneous operation.No optimization option is enabled.
Thanks,
-AD
Can only guess without actually seeing the code, but here are 2 possibilities:
the global variable is being hidden by a local in either main() or func2() (or maybe func1() - the question mentions func1() but I suspect that's a typo - this is why cutting and pasting code is quite important);
you are mistakenly declaring the global variable as static in file1.c and have an initializer on your extern declaration in file2.c. Having an initializer on the extern declaration will cause that declaration to be a definition, too.
Maybe try declaring it volatile (not sure if that's even valid for globals) and disable any compiler optimizations in case it's getting tricky somehow.
If the variable has a different address in different translation units, you are not seeing one but at least two variables with the same name.
Most common cause: You may have accidently declared a local variable on the stack with the same name. Check your code for this. If the variables are really global the linker should complain if two translation units contain the same symbol.
If this does not help, and if you still see multiple copies of the same symbol-name it's probably best to take a look at the map file (can be enabled in the linker-settings).
All external symbols are listed there with their name, address and (most important in your case) the object-file that contained them.
The addresses in the map-file may be just offsets. In this case do all your calculations relative to a symbol that is known to exist only once. the main() entrypoint might be good for this.
Probably a typo or some thing similar in your code. Try this working demo:
file1.c
int variable;
void fun1(int k);
int main()
{
printf("%d\n", variable);
fun1(4);
printf("%d\n", variable);
}
file2.c
extern int variable;
void fun1(int k)
{
variable = k;
}
Output:
0
4
To compile:
cl.exe file1.c file2.c

Resources