How does the local static variables are stored - c

If I declare a global variable as static it will be stored in data segment. And all the functions in that file can access it. no issues so far....
If, inside a function if we declare a static variable, as shown below:
int foo()
{
static int a;
.
.
}
so this variable "a" also stored in data segment (please correct me if I am wrong).
my question is, if the global static variable which is stored in data segment is accessible across the functions.
But the static variable which is defined inside the function which is also stored in data segment, is not accessible across the functions, why?

That is because of SCOPE
Scope is the region or section of the code where a variable can be accessed. There can be
File Scope
Function Scope
Block Scope
Program Scope
Prototype Scope
Example
#include<stdio.h>
#include<conio.h>
void function1()
{
printf("In function1\n");
}
static void function2()
{
printf("In function2\n");
{
int i = 100;
Label1:
printf("The value of i =%d\n",i);
i++;
if(i<105)
goto Label1;
}
}
void function3(int x, int y);
int main(void)
{
function1();
function2();
getch();
return 0;
}
In the example,
‘function1()’ has ‘Program Scope’.
‘function2()’ has ‘File Scope’.
‘Label1’ has ‘Function Scope’. (Label names must be unique within the
functions. ‘Label’ is the only identifier that has function scope.
Variable ‘i’ has ‘Block Scope’.
Variable ‘x’ and ‘y’ has ‘Prototype Scope’. There cannot be two
variables with the name ‘x’ or ‘y’ in the function parameter list.

Its just a rule the compiler and linker implement. For one thing you can have multiple static variables in different functions with the same name.

Related

How to globaly initialize variable in c and what is the difference between static and extern?

please explain me about how a variable scope can be globally initialized in C and what is the difference between static and extern
The scope of variable means: Where can it be seen (aka where does it exist) and thereby be accessed.
The scope of a variable depends on where in the code it is defined.
A variable gets global scope when it is defined outside a function. The keyword static can limit the scope of a global variable so that it can only be seen in that particular c-file (aka compilation unit). So:
file1.c
int gInt1; // Global variable that can be seen by all c-files
static int gInt2; // Global variable that can be seen only by this c-file
void foo(void)
{
int lInt; // Local variable
...
}
In order to use a global variable from another c-file, you tell the compiler that it exists in some other file. For this you use the extern keyword.
file2.c
extern int gInt1; // Now gInt1 can be used in this file
void bar(void)
{
int n = gInt1 * (gInt1 + 1);
...
}
You often put the extern declaration into a header file. Like:
file1.h
extern int gInt1; // Any c-file that includes file1.h can use gInt1
file2.c
#include "file1.h" // Now gInt1 can be used in this file
void bar(void)
{
int n = gInt1 * (gInt1 + 1);
...
}
Regarding initialization
Initializing a global variable is no different from initializing a local variable.
The only difference between global and local variables is when you do not have an initializer. In such cases a local variable will be left uninitialized while global variables will be default initialized (which typically means initialized to zero).
file1.c
int gInt1 = 42; // Global variable explicit initialized to 42
int gInt2; // Global variable default initialized to 0
void foo(void)
{
int lInt1 = 42; // Local variable explicit initialized to 42
int lInt2; // Local variable uninitialized. Value is ??
...
}
To Declare a variable of global scope ,just declare it outside all functions.
Intial value -0.
Scope of Global variable: It can be used in all functions and files.
Life- Till Program execution.
Use of extern keyword:
If you declared a global variable in a file and want to use it in another file then extern keyword is used.
int x=5; //source file
extrern int x=10; //any other file
Another use of extern keyword is if the golbal variable is used before declaration in program.
example:
void main()
{
int x
extern int y;
x=y;
}
int y=5;
Static varialbe:
intial value-0
scope- Till control remain in block,function or file.
Life -Till Program execution.
void main()
{
fun();
fun();
fun();
}
void fun()
{
int x=0;
x++;
}
After Program ends x=3.
Static Variable can also be used as global variable and declared outside all functions
but the scope remain in the file in which it is defined.
example:
static int x=2;
int main()
{
x=5;
}
That's all!

Can we define function prototype in main function in C?

in my university our teacher taught us "we define function prototype before main function. Like:
#include<stdio.h>
void findmax(float, float);
int main()
{
//code goes here
}
But today my friend showed me they learned they put prototype inside main function. Like:
#include<stdio.h>
int main()
{
void findmax(float, float);
float firstnum, secondnum;
printf("Enter first:");
scanf("%f", &firstnum);
printf("Enter second:");
scanf("%f", &secondnum);
findmax(firstnum, secondnum);
}
void findmax(float x, float y)
{
float maxnum;
if(x>y)
{
maxnum=x;
}
else
{
maxnum=y;
}
printf("The max is %f", maxnum);
}
They both works.I wonder if there are differences between them. Thanks.
Can we define function prototype in main function in C?
Yes.
I wonder if there are differences between them
The difference is that in first snippet prototype is global while in second it is local to main. findmax will be visible after its declaration and/or definition.
#include<stdio.h>
void foo();
int main()
{
void findmax(float, float);
foo();
findmax(10, 20); // It knows findmax by the prototype declared above
}
void findmax(float x, float y)
{
float maxnum;
if(x>y)
maxnum=x;
else
maxnum=y;
printf("The max is %f", maxnum);
}
void foo(){ // foo is using findmax after its definition.
findmax(12, 30);
}
If foo is declared in outside a function, it can be called from any function in the same file:
void foo(); // <-- global declaration
int main() {
foo(); // <-- works, foo() is declared globally
}
void otherfunc() {
foo(); // <-- works, foo() is declared globally
}
However, if foo is declared inside a function, it can only be used within the same scope:
int main() {
void foo(); // <-- scoped declaration
foo(); // works, foo() is declared in same scope
}
void otherfunc() {
foo(); // ERROR: foo() is not declared in scope of otherfunc()
}
In either case, foo must be declared before it is used.
If you declare the function in main() it is scoped in the main() and you cannot access it in another function. But if you declare it at the start of the file or in a header file you can use it in any function.
A straightforward answer to your question would simply be a YES. But when it comes to the scope, I'd like to add more.
What others suggest is right -- if you declare a function inside another function, the first one's scope is usually limited to the second one. For the example you provided, it is perfectly safe to say so. But that may not be the case always. Consider the following code:
#include <stdio.h>
/* Can be accessed from anywhere in this file
* because defined before anything else.
*/
void print_hello() {
puts("Hello!");
}
int main() {
void print_hello(); /* Not needed actually */
void print_namaste();
void print_hi();
print_namaste();
print_hi();
}
/* The following two functions cannot be
* accessed from within the above two functions
* unless these two are declared inside them
* or at the starting of this file
*/
void print_namaste() {
puts("Namaste!");
print_hello();
}
void print_hi() {
puts("Hi!");
}
Here you can see that print_hello() is declared inside main(). But that is redundant. print_hello() has already been introduced into the compiler. There is no need of declaration to use it inside this file (if you use it inside other files and compile them independently, then you'll have to declare it inside those files or write a header file to do so). What my point is, declaring print_hello() inside main() has not rendered it local, at least in this example. You can see print_namaste() calling it successfully without any additional declaration.
But that is not the case with print_namaste() and print_hi(). They require declaration to be used from within main() because they are introduced to the compiler only after main() has been defined.
print_namaste() will only be visible to the functions inside which we declare it, and to those functions which are defined after print_namaste(). In this example, print_namaste() is not visible to print_hello() (unless declared inside it or before it), but visible to main() because declared inside it, and visible to print_hi because its definition comes only after the definition of print_namaste().
In VC2008 the following is valid:
int main(void)
{
void foo(void);
//...
}
void test(void)
{
foo();
}
My believe was that prototype declarations are valid anywhere and their scope is at least from the point of declaration to the end of file.
Looking at the C99 standard:
6.2.1 Scope of Identifiers
An identifier can denote an object; a function; a tag or a member of a structure, union, or
enumeration; a typedef name; a label name; a macro name; or a macro parameter... For each different entity that an identifier designates, the identifier is visible (i.e., can be
used) only within a region of program text called its scope... identifier has scope determined by the placement of its declaration (in a
declarator or type specifier). If the declarator or type specifier that declares the identifier
appears outside of any block or list of parameters, the identifier has file scope, which
terminates at the end of the translation unit. If the declarator or type specifier that
declares the identifier appears inside a block or within the list of parameter declarations in
a function definition, the identifier has block scope, which terminates at the end of the
associated block.
This would mean that VC2008 is wrong.

where to declare structures, inside main() or outside main()?

Case 1: structure declared outside main() working fine
#include<stdio.h>
#include<conio.h>
struct prod
{
int price,usold;
};
int main()
{
struct prod *p,a;
int billamt(struct prod *);
int bill;
printf("enter the values \n");
scanf("%d%d",&p->price,&p->usold);
bill=billamt(p);
printf("bill=%d",bill);
getch();
}
int billamt(struct prod *i)
{
int b;
b=(i->price*i->usold);
return b;
}
Case 2: declared inside main() giving error
[Error] type 'main()::prod' with no linkage used to declare function 'int billamt(main()::prod*)' with linkage [-fpermissive]*
#include<stdio.h>
#include<conio.h>
int main()
{
struct prod
{
int price,usold;
};
struct prod *p,a;
int billamt(struct prod *);
int bill;
printf("enter the values \n");
scanf("%d%d",&p->price,&p->usold);
bill=billamt(p);
printf("bill=%d",bill);
getch();
}
int billamt(struct prod *i)
{
int b;
b=(i->price*i->usold);
return b;
}
where to declare structures, inside main() or outside main()?
First thing, I think you meant "define", not "declare".
Second, there is no rule as such, You can define wherever you want. It is all about the scope of the definition.
If you define the structure inside main(), the scope is limited to main() only. Any other function cannot see that definition and hence, cannot make use of that structure definition.
If you define the structure in a global scope, (i.e., outside main() or any other function, for that matter), that definition is available globally and all the functions can see and make use of the structure definition.
It have to do about scoping, when you define the structure inside the main function then it's only defined in the scope of the main function, so the billamt function can't know about it.
Structure are a like array only the main difference in Array can hold only same type of values but a structure can have different types of values so if you need to implement structure globally(by globally i mean it can be used in any other function too) define it outside the main and if you want to use your structure only in the main function define it inside it.
Happy Coding :-)

C data segment identification

If I declare
static int a ;// globally and
static int a ; // locally in one function
So now there are two instances of a ..
I know all static variables goes into data segment but how they are differentiated in data segment which one is local and which one is global ??
You can in fact go further: you can declare
static int a;
at file scope in two or more separate files contributing to your program. Each such declaration in a different scope declares a separate variable. Thus, given
f.c:
static int a;
int f() {
static int a;
return 0;
}
main.c
static int a;
int f(void);
int main() {
return f();
}
There are three separate static variables associated with the name a in different places. It is the compiler and linker's job to arrange for the correct storage to be associated with each variable reference.

Why does defining a typedef with the same name as a function give an error when the typedef is global but not local?

When I compile the first code I don't get any error
#include <stdio.h>
void bool_t(void)
{
printf("This is a test\n ");
}
int main()
{
typedef enum bool_t
{
false=0,true=1
} bool_t;
bool_t x = true;
return 0;
}
But when I compile the second code I get an error
#include <stdio.h>
void bool_t(void)
{
printf("la valeur est ");
}
typedef enum bool_t
{
false=0,true=1
} bool_t;
int main()
{
bool_t x = true;
return 0;
}
The error is
error: ‘bool_t’ redeclared as different kind of symbol
I would like really to understand what happened exactly in the first and second code to understand more the behavior of the two implementations as I consider myself a beginner in C!
In the first case bool_t is declared inside a function scope, so it shadows declaration from outer scope. This is useful, because it means that adding independent symbols to outer scope won't make your function invalid.
In the second case you are declaring bool_t twice in the same scope - global scope. This is not allowed.
In first case your overriding global bool_t function with local enum type bool_t.
But in second case your are declaring bool_t twice in global scope, which is an error as compiler pointed you out.
This is due to resolution of scope that's they called. In the first code you have used two same name but in different scope so they are treated as different and local variable gets preference.
In the second case the scope is same global so declaring two same named variable with different data type the compiler would not allow it.

Resources