Showing posts with label Storage Class in c. Show all posts
Showing posts with label Storage Class in c. Show all posts

Sunday, 24 December 2017

Constant in C/C++

Constant is a variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc.

Every constant has some range. The integers that is too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under signed bit the range of an int, varies from -128 to +127 and under unsigned bit int varies from 0 to 255.

Defining Constants

In C program we can define constants in two ways as shown below:
  • Using #define preprocessor directive
  • Using a const keyword.
Let us now learn about above two ways in details:

Using #define preprocessor directive : This directive used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:

#define VarName value

where Varname is the name given to constant and value is any value assigned to it.

Below is the C program to explain how to use #define to declare constants:

#include<stdio.h>
#define val 10
#define floatVal 4.5
#define charVal 'G'

int main()
{
printf("Integer Constant: %d\n",val);
printf("Floating point Constant: %f\n",floatVal);
printf("Character Constant: %c\n",charVal);

return 0;
}

 

Output:
 

Integer Constant: 10
Floating point Constant: 4.500000
Character Constant: G

 

Read Macros and Preprocessors directives in C.

 Using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. Below program shows how to use const to declare costants of different data types:

#include<stdio.h>
int main()
{
const int intVal = 10; // int constant
const float floatVal = 4.14; // Real constant
const char charVal = 'A'; // char constant
const char stringVal[10] = "ABC"; // string constant

printf("Integer constant :%d \n", intVal );
printf("Floating point constant : %f \n", floatVal );
printf("Character constant : %c \n", charVal );
printf("String constant : %s \n", stringVal);

return 0;
}

 

Output:
 

Integer constant :10
Floating point constant : 4.140000
Character constant : A
String constant : ABC

 

Learn about Const Qualifier in C.
 

String Literals : When string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read only block (generally in data segment) that is shared among functions.
 

char *str = "GfG";
 

In the above line “GfG” is stored in a read only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in program.
 

The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory.
 

int main()
{
char *str;

/* Stored in read only part of data segment */
str = "GfG";

/* Problem: trying to modify read only memory */
*(str+1) = 'n';
return 0;
}


Extern keyword in C / C++

Keyword extern is used for declaring extern variables in c. This modifier is used with all data types like int, float, double, array, pointer, structure, function etc.

Facts about extern keyword:

1. It is default storage class of all global variables as well all functions.

For example, Analyze following second.c code and its output:

(a)

#include <stdio.h>

int a; //By default it is extern variable

int main(){

printf("%d",a);

return 0;

}


Output: 0

(b)

#include <stdio.h>

extern int a;//extern variable

int main(){

printf("%d",a);

return 0;

}


Output: Compilation error, undefined symbol i.

In Both program variable a is extern variable. Read second and third points for explaination.

(c)
#include <stdio.h>

void add(int,int) //extern by default.

int main(){

int x=15,y=10;

add(x,y);

return 0;

}


void sum(int x,int y){

printf("%d”",x+y);

}

Output: 25

1. When we use extern with any variables it is only declaration that is memory is not allocated for that variable. Hence in second case compiler is showing error unknown symbol a. To define a variable i.e. allocate the memory for extern variables it is necessary to initialize the variables. For example:

#include <stdio.h>

extern int a=1000; //extern variable

int main(){

printf("%d",a);

return 0;

}


Output: 1000

3. If you will not use extern keyword with global variables then compiler will automatically initialize with default value to extern variable.

4. Default initial value of extern integral type variable is zero otherwise null. For example:

#include <stdio.h>

char c;

int i;

float f;

char *str;

int main(){

printf("%d %d %f %s",c,i,f,str);

return 0;

}


Output: 0 0 0.000000 (null)

5. We cannot initialize extern variable locally i.e. within any block either at the time of declaration or separately. We can only initialize extern variable globally. For example:

(a)

#include <stdio.h>

int main(){

extern int i=10; //Try to initialize extern variable

//locally.

printf("%d",i);

return 0;

}

Output: Compilation error: Cannot initialize extern variable.

(b)

#include <stdio.h>

int main(){

extern int i; //Declaration of extern variable i.

int i=10; //Try to locally initialization of

//extern variable i.

printf("%d",i);

return 0;

}


Output: Compilation error: Multiple declaration of variable i.

6. If we declare any variable as extern variable then it searches that variable either it has been initialized or not. If it has been initialized which may be either extern or static* then it is ok otherwise compiler will show an error. For example:

(a)

#include <stdio.h>

int main(){

extern int i; //It will search the initialization of

//variable i.

printf("%d",i);

return 0;

}

int i=20; //Initialization of variable i.
Output: 20

(b)

#include <stdio.h>

int main(){

extern int i; //It will search the any initialized

//variable i which may be static or

//extern.

printf("%d",i);

return 0;

}

extern int i=20; //Initialization of extern variable i.


Output: 20

(c)

#include <stdio.h>

int main(){

extern int i; //It will search the any initialized

//variable i which may be static or

//extern.

printf("%d",i);

return 0;

}

static int i=20; //Initialization of static variable i.

Output: 20

(d)

#include <stdio.h>

int main(){

extern int i; //variable i has declared but not

//initialized

printf("%d",i);

return 0;

}


Output: Compilation error: Unknown symbol i.


7. A particular extern variable can be declared many times but we can initialize at only one time. For example:

(a)

extern int i; //Declaring the variable i.

int i=25; //Initializing the variable.

extern int i; //Again declaring the variable i.

#include


int main(){

extern int i; //Again declaring the variable i.

printf("%d",i);

return 0;

}


Output: 25


(b)

extern int i; //Declaring the variable

int i=25; //Initializing the variable

#include


int main(){

printf("%d",i);

return 0;

}

int i=20; //Initializing the variable

Output: Compilation error: Multiple initialization variable i.

8. We cannot write any assignment statement globally. For example:

#include <stdio.h>

extern int i;

int i=10; //Initialization statement

i=25; //Assignment statement

int main(){

printf("%d",i);

return 0;

}

Output: Compilation error

Note: Assigning any value to the variable at the time of declaration is known as initialization while assigning any value to variable not at the time of declaration is known assignment.

(b)

#include <stdio.h>

extern int i;

int main(){

i=25; //Assignment statement

printf("%d",i);

return 0;

}


int i=10; //Initialization statement

Output: 25

9. If declared an extern variables or function globally then its visibility will whole the program which may contain one file or many files. For example consider a c program which has written in two files named as first.c and second.c:

(a)
//first.c
#include


int i=25; //By default extern variable

int j=5; //By default extern variable

/**

Above two line is initialization of variable i and j.

*/

void main(){

clrscr();

sum();

getch();

}




//second.c

#include


extern int i; //Declaration of variable i.

extern int j; //Declaration of variable j.

void sum(){

int s;

s=i+j;

printf("%d",s);

}


Compile and execute above two file first.c and second.c at the same time:



Storage Classes in C

A storage class defines the scope or visibility and life-time of variables and or a functions within a C Program. They prefix data type . There four different storage classes in a C program −
  • auto
  • register
  • static
  • extern

Auto Storage Class

The auto storage class is the default storage class for all local variables. And use of it does not change anything for normal local variable.

int main()
{
int mount;
auto int month;
}

The above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables.

Register Storage Class

 The register storage class is used to store local variables on register instead of RAM. This means that the variable has a maximum size equal to the register size and can't use unary '&' operator to get its memory location.

{
register int miles;
}

The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

Static Storage Class

Static variables have a property of preserving their value even after they are out of their scope. Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

Syntax:
static data_type var_name = var_value;

Following are some interesting facts about static variables in C.

  •   A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.
For example, we can use static int to count number of times a function is called, but an auto variable can’t be sued for this purpose.

For example below program prints “1 2”

#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}

int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

 

Output:
 

1 2
But below program prints 1 1

 

#include<stdio.h>
int fun()
{
int count = 0;
count++;
return count;
}

int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}

 

Output:
 

1 1

  • Static variables are allocated memory in data segment, not stack segment.
  • Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage.

#include <stdio.h>

 int main()
{
static int x;
int y;
printf("%d \n %d", x, y);
}

 

Output:
 

0
[some_garbage_value]


  • In C, static variables can only be initialized using constant literals. For example, following program fails in compilation.
  #include <stdio.h>
int initializer(void)
{
return 50;
}

int main()
{
static int i = initializer();
printf(" value of i = %d", i);
getchar();
return 0;
}

 

Output
 

In function 'main':
error: initializer element is not constant
static int i = initializer();
^

Please note that this condition doesn’t hold in C++. So if you save the program as a C++ program, it would compile \and run fine.

  • Static global variables and functions are also possible in C/C++. The purpose of these is to limit scope of a variable or function to a file. Please refer Static functions in C for more details.

Extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.
 

When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.
 

Please refer Extern keyword for more details

Geeks4Coding

Contributors

Popular Posts