Hi guys,
I have a few doubts in C.
======
Questions, not doubts. "Question" means you don't know something, and
you ask people to find out. "Doubt" means you have some information, but
you don't quite believe it. For example, if I tell you that I can
multiply ten digit numbers by head then you will doubt that (you don't
believe it, but it might just be true). If I tell you that I can
multiply thousand digit numbers in my head then you don't just doubt it,
you will know it is not true.
1. Why static declartions are not allowed inside structs?
eg
struct a {
static int i;
};
Because it wouldn't be meaningful. "static" is used for functions and
variables that exist permanently, but whose names can be used only in
one file. A struct doesn't declare a variable, instead it gives a list
of components that will be there in any variable of that struct type.
2.How does the complier diffrenciate between a Global Variable and
Static Variable as both of them will be in the same stack?
=================
They won't be in a "stack" at all. They are there permanently while your
program runs; stacks are used for situations when things are added and
removed again in exactly the opposite order of adding them. For example,
if you call a function then all the local variables start existing when
the function is called and they stop to exist when the function returns;
these variables would likely be in a stack, but global and static
variables are not in a stack.
The difference between global and static: When you have a global
variable x, the compiler remembers "global variable x". If you use the
global variable x in two files, then it is "global variable x" each
time, so it is the same variable. When you have a static variable x in
file a, then the compiler remembers "static variable x in file a"; if
you use a static variable x in file b the compiler remembers "static
variable x in file b". Both are separate things.
Static variables are useful because they cannot be used in different
files by accident. Lets say you used a global int x in some code.
Someone else might need a global variable in his or her code and also
call it x. If both codes are used in the same program, then you will
have a problem because the other persons code will change your global
variable. With static variables, you don't have that problem.