Lecture-24
Unions, Storage Classes
Unions
• Union is a collection of variables of different data
types, in case of union information can only be
stored In one field at any one time.
• A union is a special data type available in C that
enables you to store different data types in the same
memory location.
• You can define a union with many members, but only
one member can contain a value at any given time.
Unions provide an efficient way of using the same
memory location for multi-purpose.
Defining a Union
To define a union, you must use the union statement in
the same way as you did while defining a structure. The
union statement defines a new data type with more
than one member for your program. The format of the
union statement is as follows
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a
normal variable definition, such as int i; or float f; or any other
valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union
variables but it is optional.
Example:
union Data
{
int i;
float f;
char str[20];
} data;
The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in the above example, Data type will
occupy 20 bytes of memory space because this is the maximum space which
can be occupied by a character string.
Accessing Union Members
To access any member of a union, we use the member
access operator (.).
The member access operator is coded as a period
between the union variable name and the union
member that we wish to access.
The keyword union is used to define variables of union
type.
The following example shows how to use unions
in a program
#include <stdio.h>
#include <string.h>
union Data
{ int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %dn", data.i);
printf( "data.f : %fn", data.f);
printf( "data.str : %sn", data.str);
return 0;
}
Output
data.i : 1917853763
data.f :
4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values
of i and f members of union got corrupted
because the final value assigned to the
variable has occupied the memory location
and this is the reason that the value
of str member is getting printed very well.
example for using one variable at a time
#include <stdio.h>
#include <string.h>
union Data
{ int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %dn", data.i);
data.f = 220.5;
printf( "data.f : %fn", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %sn", data.str);
return 0;
}
Here, all the members are getting printed very well because one member is being used
at a time.
Output
data.i : 10
data.f : 220.500000
data.str : C Programming
Differences between Structure and Union
Key Structure Union
Definition
Structure is the container defined in C
to store data variables of different type
and also supports for the user defined
variables storage
On other hand Union is also similar
kind of container in C which can also
holds the different type of variables
along with the user defined variables.
Internal
implemen
tation
Structure in C is internally
implemented as that there is separate
memory location is allotted to each
input member
While in case Union memory is
allocated only to one member having
largest size among all other input
variables and the same location is
being get shared among all of these.
Syntax Syntax of declare a Structure in C is as
follow :struct struct_name{ type
element1; type element2; . . }
variable1, variable2, ...;
On other syntax of declare a Union in C
is as follow:union u_name{ type
element1; type element2; . . }
variable1, variable2,…..;
Differences between Structure and Union
Key Structure Union
Size As mentioned in definition Structure
do not have shared location for its
members so size of Structure is equal
or greater than the sum of size of all
the data members.
On other hand Union does not
have separate location for each of
its member so its size or equal to
the size of largest member among
all data members.
Value storage As mentioned above in case of
Structure there is specific memory
location for each input data member
and hence it can store multiple values
of the different members.
While in case of Union there is only
one shared memory allocation for
all input data members so it stores
a single value at a time for all
members
Initialization In Structure multiple members can be
can be initializing at same time.
On other hand in case of Union
only the first member can get
initialize at a time.
Storage Classes
A storage class defines the scope (visibility) and life-time
of variables and/or functions within a C Program. They
precede the type that they modify. We have four
different storage classes in a C program −
– auto
– Static
– register
– extern
Example:
storage_class datatype variable_name;
Auto Storage Class
The auto storage class is the default storage class for all local
variables.
Syntax to declare automatic variable is:
auto datatype variablename;
Example:
auto int i;
Features of Automatic Storage Class are as follows
• Storage: Memory
• Default Initial Value: Garbage Value
• Scope: Local to the block in which the variable is defined
• Life: Till the control remains within the block in which the
variable is defined
The following program illustrates the work of automatic
variables.
void test();
void main()
{
test();
test();
test();
}
void test()
{
auto int k=10;
printf(“%dn”,k);
k++;
}
Output
10
10
10
Static Storage Class
• The static storage class instructs the compiler to keep a
local variable in existence during the life-time of the
program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local
variables static allows them to maintain their values
between function calls.
• The static modifier may also be applied to global variables.
When this is done, it causes that variable's scope to be
restricted to the file in which it is declared.
Syntax to declare static variable is:
static datatype variablename;
Example:
static int i;
Features of Static Storage Class are as follows
Storage: Memory
Default Initial Value: Zero
Scope: Local to the block in which the variable is
defined
Life: Value of the variable continues to exist between
different function calls
The previous program with k is declared as static
instead of automatic.
void test();
void main()
{
test();
test();
test();
}
void test()
{
static int k=10;
printf(“%dn”,k);
k++;
}
Output
10
11
12
The register Storage Class
The register storage class is used to define local
variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size
equal to the register size (usually one word) and can't
have the unary '&' operator applied to it (as it does not
have a memory location).
Syntax to declare register variable is:
register datatype variablename;
Example:
register int miles;
Features of Register Storage Class are as follows:
Storage: CPU Registers
Default Initial Value: Garbage Value
Scope: Local to the block in which the variable is
defined
Life: Till the control remains within the block in which
the variable is defined
The 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.
• The extern modifier is most commonly used when
there are two or more files sharing the same global
variables or functions
Syntax to declare static variable is:
extern datatype variablename;
Example:
extern int i;
Features of External Storage Class are as follows
Storage: Memory
Default Initial Value: Zero
Scope: Global
Life: Till the program’s execution doesn’t come to
an end
Example of external storage class
First File: main.c
#include <stdio.h>
int count ;
extern void
write_extern();
main()
{ count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void)
{
printf("count is %dn",
count);
}
When this program is executed the output is -count is 5
Properties of different storage classes
Storage
Class
Storage Default
Initial
Value
Scope Life
Automa
tic
Memory Garbage
Value
Local to the block in
which the
variable is defined
Till the control remains within
the block in which the variable
is defined
Register CPU
Registers
Garbage
Value
Local to the block in
which the
variable is defined
Till the control remains within
the block in which the variable
is defined
Static Memory Zero Value of the variable
continues to exist
between different
function calls
Value of the variable continues
to exist between different
function calls
External
Memory Zero
Global Till the program’s execution
doesn’t come to an end

Lesson 26 c programming ( union, storage classes)

  • 1.
  • 2.
    Unions • Union isa collection of variables of different data types, in case of union information can only be stored In one field at any one time. • A union is a special data type available in C that enables you to store different data types in the same memory location. • You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.
  • 3.
    Defining a Union Todefine a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows union [union tag] { member definition; member definition; ... member definition; } [one or more union variables];
  • 4.
    The union tagis optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Example: union Data { int i; float f; char str[20]; } data; The memory occupied by a union will be large enough to hold the largest member of the union. For example, in the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by a character string.
  • 5.
    Accessing Union Members Toaccess any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. The keyword union is used to define variables of union type.
  • 6.
    The following exampleshows how to use unions in a program #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; data.f = 220.5; strcpy( data.str, "C Programming"); printf( "data.i : %dn", data.i); printf( "data.f : %fn", data.f); printf( "data.str : %sn", data.str); return 0; } Output data.i : 1917853763 data.f : 4122360580327794860452759994368.000000 data.str : C Programming Here, we can see that the values of i and f members of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of str member is getting printed very well.
  • 7.
    example for usingone variable at a time #include <stdio.h> #include <string.h> union Data { int i; float f; char str[20]; }; int main( ) { union Data data; data.i = 10; printf( "data.i : %dn", data.i); data.f = 220.5; printf( "data.f : %fn", data.f); strcpy( data.str, "C Programming"); printf( "data.str : %sn", data.str); return 0; } Here, all the members are getting printed very well because one member is being used at a time. Output data.i : 10 data.f : 220.500000 data.str : C Programming
  • 8.
    Differences between Structureand Union Key Structure Union Definition Structure is the container defined in C to store data variables of different type and also supports for the user defined variables storage On other hand Union is also similar kind of container in C which can also holds the different type of variables along with the user defined variables. Internal implemen tation Structure in C is internally implemented as that there is separate memory location is allotted to each input member While in case Union memory is allocated only to one member having largest size among all other input variables and the same location is being get shared among all of these. Syntax Syntax of declare a Structure in C is as follow :struct struct_name{ type element1; type element2; . . } variable1, variable2, ...; On other syntax of declare a Union in C is as follow:union u_name{ type element1; type element2; . . } variable1, variable2,…..;
  • 9.
    Differences between Structureand Union Key Structure Union Size As mentioned in definition Structure do not have shared location for its members so size of Structure is equal or greater than the sum of size of all the data members. On other hand Union does not have separate location for each of its member so its size or equal to the size of largest member among all data members. Value storage As mentioned above in case of Structure there is specific memory location for each input data member and hence it can store multiple values of the different members. While in case of Union there is only one shared memory allocation for all input data members so it stores a single value at a time for all members Initialization In Structure multiple members can be can be initializing at same time. On other hand in case of Union only the first member can get initialize at a time.
  • 10.
    Storage Classes A storageclass defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program − – auto – Static – register – extern Example: storage_class datatype variable_name;
  • 11.
    Auto Storage Class Theauto storage class is the default storage class for all local variables. Syntax to declare automatic variable is: auto datatype variablename; Example: auto int i; Features of Automatic Storage Class are as follows • Storage: Memory • Default Initial Value: Garbage Value • Scope: Local to the block in which the variable is defined • Life: Till the control remains within the block in which the variable is defined
  • 12.
    The following programillustrates the work of automatic variables. void test(); void main() { test(); test(); test(); } void test() { auto int k=10; printf(“%dn”,k); k++; } Output 10 10 10
  • 13.
    Static Storage Class •The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls. • The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared. Syntax to declare static variable is: static datatype variablename; Example: static int i;
  • 14.
    Features of StaticStorage Class are as follows Storage: Memory Default Initial Value: Zero Scope: Local to the block in which the variable is defined Life: Value of the variable continues to exist between different function calls
  • 15.
    The previous programwith k is declared as static instead of automatic. void test(); void main() { test(); test(); test(); } void test() { static int k=10; printf(“%dn”,k); k++; } Output 10 11 12
  • 16.
    The register StorageClass The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location). Syntax to declare register variable is: register datatype variablename; Example: register int miles;
  • 17.
    Features of RegisterStorage Class are as follows: Storage: CPU Registers Default Initial Value: Garbage Value Scope: Local to the block in which the variable is defined Life: Till the control remains within the block in which the variable is defined
  • 18.
    The extern StorageClass • 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. • The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions
  • 19.
    Syntax to declarestatic variable is: extern datatype variablename; Example: extern int i; Features of External Storage Class are as follows Storage: Memory Default Initial Value: Zero Scope: Global Life: Till the program’s execution doesn’t come to an end
  • 20.
    Example of externalstorage class First File: main.c #include <stdio.h> int count ; extern void write_extern(); main() { count = 5; write_extern(); } Second File: support.c #include <stdio.h> extern int count; void write_extern(void) { printf("count is %dn", count); } When this program is executed the output is -count is 5
  • 21.
    Properties of differentstorage classes Storage Class Storage Default Initial Value Scope Life Automa tic Memory Garbage Value Local to the block in which the variable is defined Till the control remains within the block in which the variable is defined Register CPU Registers Garbage Value Local to the block in which the variable is defined Till the control remains within the block in which the variable is defined Static Memory Zero Value of the variable continues to exist between different function calls Value of the variable continues to exist between different function calls External Memory Zero Global Till the program’s execution doesn’t come to an end