Sei sulla pagina 1di 95

C data types:

There are four data types in C language. They are,


S.no
1
2
3
4

Types
Basic data types
Enumeration data type
Derived data type
Void data type
Object 1

1. Basic data types in C:

Data Types
int, char, float, double
enum
pointer, array, structure, union
void
Object
Object17
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9

1.1. Integer data type:

Integer data type allows a variable to store numeric values.


int keyword is used to refer integer data type.
The storage size of int data type is 2 or 4 or 8 byte.
It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2
byte (16 bit) of memory will be allocated for int data type.
Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64
bit processor is allocated for int datatype.
int (2 byte) can store values from -32,768 to +32,767
int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
If you want to use the integer value that crosses the above limit, you can go for

Loop control statements in C are used to perform looping operations until the given condition is
true. Control comes out of the loop statements once condition becomes false.
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They are,
1. for
2. while
3. do-while
Syntax for each C loop control statements are given in below table with description.
S.no Loop Name Syntax

2
3

for

while
do while

Description
Where,
exp1 variable initialization
( Example: i=0, j=2, k=3 )
for (exp1; exp2; expr3)
exp2 condition checking
{ statements; }
( Example: i>5, j<3, k=3 )
exp3 increment/decrement
( Example: ++i, j, ++k )
while (condition)
where,
{ statements; }
condition might be a>5, i<10
where,
do { statements; }

while (condition);

condition might be a>5, i<10

Example program (for loop) in C:


In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}

Output:
0123456789
Example program (while loop) in C:
In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}

Output:
3456789
Example program (do while loop) in C:
In do..while loop control statement, while loop is executed irrespective of the condition for first
time. Then 2nd time onwards, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=1;

do
{
printf("Value of i is %d\n",i);

Loop control statements in C are used to perform looping operations until the given condition is
true. Control comes out of the loop statements once condition becomes false.
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They are,
1. for
2. while
3. do-while
Syntax for each C loop control statements are given in below table with description.
S.no Loop Name Syntax

for

while

2
3

do while

Description
Where,
exp1 variable initialization
( Example: i=0, j=2, k=3 )
for (exp1; exp2; expr3)
exp2 condition checking
{ statements; }
( Example: i>5, j<3, k=3 )
exp3 increment/decrement
( Example: ++i, j, ++k )
while (condition)
where,
{ statements; }
condition might be a>5, i<10
do { statements; }
where,
condition might be a>5, i<10
while (condition);

Example program (for loop) in C:


In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}

Output:
0123456789

Example program (while loop) in C:


In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}

Output:
3456789
Example program (do while loop) in C:
In do..while loop control statement, while loop is executed irrespective of the condition for first
time. Then 2nd time onwards, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
}

Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Difference between while & do while loops in C:
S.no while
Loop is executed only when condition is
1
true.
i++;

do while
Loop is executed for first time irrespective of the condition. Aft
checked.

}while(i<=4 && i>=2);


}

Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Difference between while & do while loops in C:

S.no while
do while
Loop is executed only when condition is
Loop is executed for first time irrespective of the condition. Aft
1
true.
checked.
long int and long long int for which the limits are very high.
Note:
We cant store decimal values using int data type.
If we use int data type to store decimal values, decimal values will be truncated and we will get
only whole number.
In this case, float data type can be used to store decimal values in a variable.
1.2. Character data type:
Character data type allows a variable to store only one character.
Storage size of character data type is 1. We can store only one character using character data
type.
char keyword is used to refer character data type.
For example, A can be stored using char datatype. You cant store more than one character
using char data type.
Please refer C Strings topic to know how to store more than one characters in a variable.
1.3. Floating point data type:
Floating point data type consists of 2 types. They are,
1. float
2. double
1. float:
Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the CPU as
int data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.

2. double:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double datatype is from 1E37 to 1E+37.
1.3.1. sizeof() function in C:
sizeof() function is used to find the memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf(Storage size for int data type:%d \n,sizeof(a));
printf(Storage size for char data type:%d \n,sizeof(b));
printf(Storage size for float data type:%d \n,sizeof(c));
printf(Storage size for double data type:%d\n,sizeof(d));
return 0;
}
Output:

Storage size for int data type:4


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
1.3.2. Modifiers in C:
The amount of memory space to be allocated for a variable is derived by modifiers.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount
of storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
There are 5 modifiers available in C language. They are,
1.
2.
3.
4.
5.

short
long
signed
unsigned
long long

Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on
the CPU processor (8,16, 32 and 64 bit)
S.No

C Data types

storage Size

Range

1
2
3
4
5
6
7
8
9
10
11
12
13

char
int
float
double
long double
long int
short int
unsigned short int
signed short int
long long int
signed long int
unsigned long int
unsigned long long int

1
2
4
8
10
4
2
2
2
8
4
4
8

127 to 127
32,767 to 32,767
1E37 to 1E+37 with six digits of precision
1E37 to 1E+37 with ten digits of precision
1E37 to 1E+37 with ten digits of precision
2,147,483,647 to 2,147,483,647
32,767 to 32,767
0 to 65,535
32,767 to 32,767
(2power(63) 1) to 2(power)63 1
2,147,483,647 to 2,147,483,647
0 to 4,294,967,295
2(power)64 1

2. Enumeration data type in C:


Enumeration data type consists of named integer constants as a list.
It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the
list.
Enum syntax in C:
enum identifier [optional{ enumerator-list }];
Enum example in C:
enum month { Jan, Feb, Mar }; or
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */
The above enum functionality can also be implemented by #define preprocessor directive as
given below. Above enum example is same as given below.
#define Jan 20;
#define Feb 21;
#define Mar 22;

C enum example program:


#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf(Value of Jan);
else if(month == 1)
printf(Month is Feb);
if(month == 2)
printf(Month is Mar);
}
Output:

Month is March
3. Derived data type in C:
Array, pointer, structure and union are called derived data type in C language.
To know more about derived data types, please visit C Array , C Pointer , C
Structure and C Union topics in this tutorial.
4. Void data type in C:
Void is an empty data type that has no value.
This can be used in functions and pointers.
Please visit C Function topic to know how to use void data type in function with simple call
by value and call by reference example programs.
C tokens, Identifiers and Keywords are the basics in a C program. All are explained in this page with
definition and simple example programs.
1. C tokens:
C tokens are the basic buildings blocks in C language which are constructed together to write a
C program.
Each and every smallest individual units in a C program are known as C tokens.
C tokens are of six types. They are,
1.
2.
3.
4.
5.
6.

Keywords
(eg: int, while),
Identifiers
(eg: main, total),
Constants
(eg: 10, 20),
Strings
(eg: total, hello),
Special symbols (eg: (), {}),
Operators
(eg: +, /,-,*)

C tokens example program:


int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (Total = %d \n, total);
}
where,

main identifier
{,}, (,) delimiter
int keyword
x, y, total identifier
main, {, }, (, ), int, x, y, total tokens

Do you know how to use C token in real time application programs? We have given simple real time
application programs where C token is used. You can refer the below C programs to know how to use C
token in real time program.
Real time application C programs for your reference:
1. C program example Real time Calculator program
2. C program example Real time Bank Application program
2. Identifiers in C language:
Each program elements in a C program are given a name called identifiers.
Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a
name given to integer variable in above program.
Rules for constructing identifier name in C:
1.
2.
3.
4.

First character should be an alphabet or underscore.


Succeeding characters might be digits or letter.
Punctuation and special characters arent allowed except underscore.
Identifiers should not be keywords.

3. Keywords in C language:
Keywords are pre-defined words in a C compiler.
Each keyword is meant to perform a specific function in a C program.
Since keywords are referred names for compiler, they cant be used as variable name.
C language supports 32 keywords which are given below. Click on each keywords below for detail
description and example programs.

auto double
break
case

else

int
long

struct

const

switch continue

float short unsigned


for signed

enum register typedef default goto sizeof

char extern return

union

do

if

static

void
volatile
while

C Constants are also like normal variables. But, only difference is, their values can not be modified by
the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
S.no
1

2
3
4
5
6

Constant type

data type
int
unsigned int
Integer constants
long int
long long int
float
Real or Floating point constants
doule
Octal constant
int
Hexadecimal constant
int
character constants
char
string constants
char

Example
53, 762, -478 etc
5000u, 1000U etc
483,647
2,147,483,680
10.456789
600.123456789
013
/* starts with 0 */
090
/* starts with 0x */
A , B, C
ABCD , Hai

Rules for constructing C constant:


1. Integer Constants in C:
An integer constant must have at least one digit.

It must not have a decimal point.


It can either be positive or negative.
No commas or blanks are allowed within an integer constant.
If no sign precedes an integer constant, it is assumed to be positive.
The allowable range for integer constants is -32768 to 32767.

2. Real constants in C:

A real constant must have at least one digit


It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.

3. Character and string constants in C:


A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single quotes.
The maximum length of a character constant is 1 character.
String constants are enclosed within double quotes.
4. Backslash Character Constants in C:
There are some characters which have special meaning in C language.
They should be preceded by backslash symbol to make use of special function of them.
Given below is the list of special characters and their purpose.
Backslash_character
\b
\f
\n
\r
\t
\
\
\\
\v
\a
\?
\N
\XN

Meaning
Backspace
Form feed
New line
Carriage return
Horizontal tab
Double quote
Single quote
Backslash
Vertical tab
Alert or bell
Question mark
Octal constant (N is an octal constant)
Hexadecimal constant (N hex.dcml cnst)

How to use constants in a C program?


We can define constants in a C program in the following ways.
1. By const keyword

2. By #define preprocessor directive


Please note that when you try to change constant values after defining in C program, it will
through error.
1. Example program using const keyword in C:
#include <stdio.h>

void main()
{
const int height = 100;
/*int constant*/
const float number = 3.14;
/*Real constant*/
const char letter = A;
/*char constant*/
const char letter_sequence[10] = ABC;
/*string
constant*/
const char backslash_char = \?;
/*special
char cnst*/
printf(value of height :%d \n, height );
printf(value of number : %f \n, number );
printf(value of letter : %c \n, letter );
printf(value of letter_sequence : %s \n, letter_sequence);
printf(value of backslash_char : %c \n, backslash_char);
}
Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
2. Example program using #define preprocessor directive in C:
#include <stdio.h>

#define height 100


#define number 3.14
#define letter A
#define letter_sequence ABC
#define backslash_char \?
void main()
{
printf(value of height : %d \n, height );
printf(value of number : %f \n, number );
printf(value of letter : %c \n, letter );
printf(value of letter_sequence : %s \n,letter_sequence);
printf(value of backslash_char : %c \n,backslash_char);
}

Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
Rules for naming C variable:
1.
2.
3.
4.
5.

Variable name must begin with letter or underscore.


Variables are case sensitive
They can be constructed with digits, letters.
No special symbols are allowed other than underscore.
sum, height, _value are some examples for variable name

Declaring & initializing C variable:


Variables should be declared in the C program before to use.
Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
Variable initialization means assigning a value to the variable.
S.No
Type
Syntax
Example
1 Variable declaration data_type variable_name;
int x, y, z; char flat, ch;
2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = x, ch=l;
There are three types of variables in C program They are,
1. Local variable
2. Global variable
3. Environment variable
1. Example program for local variable in C:
The scope of local variables will be within the function only.
These variables are declared within the function and cant be accessed outside the function.
In the below example, m and n variables are having scope within the main function only. These
are not visible to test function.
Like wise, a and b variables are having scope within the test function only. These are not visible
to main function.
#include<stdio.h>

void test();

int main()
{
int m = 22, n = 44;
// m, n are local variables of main function
/*m and n variables are having scope
within this main function only.
These are not visible to test funtion.*/
/* If you try to access a and b in this function,
you will get a undeclared and b undeclared error */
printf(\nvalues : m = %d and n = %d, m, n);
test();
}
void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope
within this test function only.
These are not visible to main function.*/
/* If you try to access m and n in this function,
you will get m undeclared and n undeclared
error */printf(\nvalues : a = %d and b = %d, a, b);
}
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
2. Example program for global variable in C:
The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
This variable is defined outside the main function. So that, this variable is visible to main
function and all other sub functions.
#include<stdio.h>

void test();int m = 22, n = 44;


int a = 50, b = 80;
int main()
{
printf(All variables are accessed from main function);
printf(\nvalues: m=%d:n=%d:a=%d:b=%d, m,n,a,b);
test();
}
void test()
{
printf(\n\nAll variables are accessed from \

test function);
printf(\nvalues: m=%d:n=%d:a=%d:b=%d, m,n,a,b);
}
Output:
All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80
3. Environment variables in C:
Environment variable is a variable that will be available for all C applications and C programs.
We can access these variables from anywhere in a C program without declaring and initializing
in an application or C program.
The inbuilt functions which are used to access, modify and set these environment variables are
called environment functions.
There are 3 functions which are used to access, modify and assign an environment variable in C.
They are,
1. setenv()
2. getenv()
3. putenv()
Example program for getenv() function in C:
This function gets the current value of the environment variable. Let us assume that environment
variable DIR is assigned to /usr/bin/test/.
#include <stdio.h>
#include <stdlib.h>

int main()
{
printf(Directory = %s\n,getenv(DIR));
return 0;
}
Output:
/usr/bin/test/
Example program for setenv() function in C:
This function sets the value for environment variable. Let us assume that environment variable
FILE is to be assigned /usr/bin/example.c
#include <stdio.h>
#include <stdlib.h>

int main()
{
setenv(FILE, /usr/bin/example.c,50);
printf(File = %s\n, getenv(FILE));
return 0;
}
Output:
File = /usr/bin/example.c
Example program for putenv() function in C:
This function modifies the value for environment variable. Below example program shows that how
to modify an existing environment variable value.
#include <stdio.h>
#include <stdlib.h>

int main()
{
setenv(DIR, /usr/bin/example/,50);
printf(Directory name before modifying = \
%s\n, getenv(DIR));
putenv(DIR=/usr/home/);
printf(Directory name after modifying = \
%s\n, getenv(DIR));
return 0;
}
Output:
Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/
Difference between variable declaration & definition in C:
S.no
Variable declaration
1 Declaration tells the compiler about data type and size of the variable.
2 Variable can be declared many times in a program.
3 The assignment of properties and identification to a variable.

Variable definition
Definition allocates memory for the v
It can happen only one time for a vari
Assignments of storage space to a var

The symbols which are used to perform logical and mathematical operations in a C program are
called C operators.
These C operators join individual constants and variables to form expressions.
Operators, functions, constants and variables are combined together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.

Types of C operators:
C language offers many types of operators. They are,
1.
2.
3.
4.
5.
6.
7.
8.

Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators

Continue on types of C operators:


Click on each operators name below for detail description and example programs.
S.no
1
2
3
4
5
6
7
8

Types of Operators
Arithmetic_operators
Assignment_operators
Relational operators
Logical operators
Bit wise operators
Conditional (ternary) operators
Increment/decrement operators
Special operators

Description
These are used to perform mathematical calculations like addition, subtract
These are used to assign the values for the variables in C programs.
These operators are used to compare the value of two variables.
These operators are used to perform logical operations on the given two va
These operators are used to perform bit operations on given two variables.
Conditional operators return one value if condition is true and returns anoth
These operators are used to either increase or decrease the value of the vari
&, *, sizeof( ) and ternary operators.

The symbols which are used to perform logical and mathematical operations in a C program are
called C operators.
These C operators join individual constants and variables to form expressions.
Operators, functions, constants and variables are combined together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.
Types of C operators:
C language offers many types of operators. They are,
1.
2.
3.
4.
5.
6.
7.
8.

Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators

Continue on types of C operators:


Click on each operators name below for detail description and example programs.
S.no
1
2
3
4
5
6
7
8

Types of Operators
Arithmetic_operators
Assignment_operators
Relational operators
Logical operators
Bit wise operators
Conditional (ternary) operators
Increment/decrement operators
Special operators

Description
These are used to perform mathematical calculations like addition, subtract
These are used to assign the values for the variables in C programs.
These operators are used to compare the value of two variables.
These operators are used to perform logical operations on the given two va
These operators are used to perform bit operations on given two variables.
Conditional operators return one value if condition is true and returns anoth
These operators are used to either increase or decrease the value of the vari
&, *, sizeof( ) and ternary operators.

In decision control statements (C if else and nested if), group of statements are executed when
condition is true. If condition is false, then else part statements are executed.
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
If, else and nested if decision control statements in C:
Syntax for each C decision control statements are given in below table with description.
Decision control statements
if

ifelse

nested if

Syntax
if (condition)
{ Statements; }
if (condition)
{ Statement1; Statement2; }
else
{ Statement3; Statement4; }
if (condition1)
{ Statement1; }
else_if(condition2)
{ Statement2; }
else Statement 3;

In these type of statements, if condition is true, then res

In these type of statements, group of statements are exe


executed.

If condition 1 is false, then condition 2 is checked and s


executed.

Example program for if statement in C:


In if control statement, respective block of code is executed when condition is
true.
int main()
{
int m=40,n=40;
if (m == n)
{

printf("m and n are equal");


}

Output:
m and n are equal
Example program for if else statement in C:
In C if else control statement, group of statements are executed when condition
is true. If condition is false, then else part statements are executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}

Output:
m and n are not equal
Example program for nested if statement in C:
In nested if control statement, if condition 1 is false, then condition 2 is
checked and statements are executed if it is true.
If condition 2 also gets failure, then else part is executed.
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}

Output:
m is greater than n

Loop control statements in C are used to perform looping operations until the given condition is
true. Control comes out of the loop statements once condition becomes false.
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They are,
1. for
2. while
3. do-while
Syntax for each C loop control statements are given in below table with description.
S.no Loop Name Syntax

for

while

2
3

do while

Description
Where,
exp1 variable initialization
( Example: i=0, j=2, k=3 )
for (exp1; exp2; expr3)
exp2 condition checking
{ statements; }
( Example: i>5, j<3, k=3 )
exp3 increment/decrement
( Example: ++i, j, ++k )
while (condition)
where,
{ statements; }
condition might be a>5, i<10
do { statements; }
where,
condition might be a>5, i<10
while (condition);

Example program (for loop) in C:


In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}

Output:
0123456789

Example program (while loop) in C:


In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}

Output:
3456789
Example program (do while loop) in C:
In do..while loop control statement, while loop is executed irrespective of the condition for first
time. Then 2nd time onwards, loop is executed until condition becomes false.
#include <stdio.h>
int main()
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
}

Output:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Difference between while & do while loops in C:

S.no while
do while
1
Loop is executed only when condition is true. Loop is executed for first time irrespective of the condition. Aft
The statements which are used to execute only specific block of statements in a series of blocks are

called case control statements.


There are 4 types of case control statements in C language. They are,
1.
2.
3.
4.

switch
break
continue
goto

1. switch case statement in C:


Switch case statements are used to execute only specific case statements based on the switch
expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
Example program for switch..case statement in C:
#include <stdio.h>

int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(Value is
break;
case 2:
printf(Value is
break;
case 3:
printf(Value is
break;
case 4:
printf(Value is
break;
default :
printf(Value is
}
return 0;
}

1 \n );
2 \n );
3 \n );
4 \n );
other than 1,2,3,4 \n );

Output:
Value is 3
2. break statement in C:
Break statement is used to terminate the while loops, switch case loops and for loops from the
subsequent execution.
Syntax: break;
Example program for break statement in C:
#include <stdio.h>

int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(\nComing out of for loop when i = 5);
break;
}
printf(%d ,i);
}
}
Output:
01234
Coming out of for loop when i = 5
3. Continue statement in C:
Continue statement is used to continue the next iteration of for loop, while loop and do-while
loops. So, the remaining statements are skipped within the loop for that particular iteration.
Syntax : continue;
Example program for continue statement in C:
#include <stdio.h>

int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{

printf(\nSkipping %d from display using \


continue statement \n,i);
continue;
}
printf(%d ,i);
}
}
Output:
01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789
4. goto statement in C:
goto statements is used to transfer the normal flow of a program to the specified label in the
program.
Below is the syntax for goto statement in C.
{
.
go to label;
.
.
LABEL:
statements;
}
Example program for goto statement in C:
#include <stdio.h>

int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf(\nWe are using goto statement when i = 5);
goto HAI;
}
printf(%d ,i);
}
HAI : printf(\nNow, we are inside label name \hai\ \n);
}

Output:
01234
We are using goto statement when i = 5
Now, we are inside label name hai
C type qualifiers : The keywords which are used to modify the properties of a variable are called type
qualifiers.
Types of C type qualifiers:
There are two types of qualifiers available in C language. They are,
1. const
2. volatile
1. const keyword:
Constants are also like normal variables. But, only difference is, their values cant be modified
by the program once they are defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Please refer C Constants topic in this tutorial for more details on const keyword.
2. volatile keyword:
When a variable is defined as volatile, the program may not change the value of the variable
explicitly.
But, these variable values might keep on changing without any explicit assignment by the
program. These types of qualifiers are called volatile.
For example, if global variables address is passed to clock routine of the operating system to
store the system time, the value in this address keep on changing without any assignment by the
program. These variables are named as volatile variable.
Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;
Storage class specifiers in C language tells the compiler where to store a variable, how to store the
variable, what is the initial value of the variable and life time of the variable.
Syntax:
storage_specifier data_type variable _name
Types of Storage Class Specifiers in C:
There are 4 storage class specifiers available in C language. They are,

1.
2.
3.
4.

auto
extern
static
register

auto

CPU Memory

Initial / default
value
Garbage value

extern

CPU memory

Zero

static

CPU memory

Zero

register

Register memory Garbage value

S. No. Storage Specifier Storage place

Scope Life
local

Within the function only.


Till
the
end
of
the
ma
Global Variable definition might be anywh
program
Retains
the
value
of
t
local
between different function calls.
local Within the function

Note:
For faster access of a variable, it is better to go for register specifiers rather than auto specifiers.
Because, register variables are stored in register memory whereas auto variables are stored in
main CPU memory.
Only few variables can be stored in register memory. So, we can use variables as register that
are used very often in a C program.
Example program for auto variable in C:
The scope of this auto variable is within the function only. It is equivalent to local variable. All local
variables are auto variables by default.
#include<stdio.h>

void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
auto int i = 0 ;
printf ( %d , i ) ;
i++;
}
Output:
0000

Example program for static variable in C:


Static variables retain the value of the variable between different function calls.
//C static example

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( %d , i ) ;
i++;
}
Output:
0123
Example program for extern variable in C:
The scope of this extern variable is throughout the main program. It is equivalent to global variable.
Definition for extern variable might be anywhere in the C program.
#include<stdio.h>

int x = 10 ;
int main( )
{
extern int y;
printf(The value of x is %d \n,x);
printf(The value of y is %d,y);
return 0;
}
int y=50;
Output:
The value of x is 10
The value of y is 50
Example program for register variable in C:
Register variables are also local variables, but stored in register memory. Whereas, auto

variables are stored in main CPU memory.


Register variables will be accessed very faster than the normal variables since they are stored in
register memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits, 32
bits or 64 bits)
#include <stdio.h>

int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf(value of arr[%d] is %d \n, i, arr[i]);
}
return 0;
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
C Array is a collection of variables belongings to the same data type. You can store group of data of
same data type in an array.

Array might be belonging to any of the data types


Array size must be a constant value.
Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
It is a best practice to initialize an array to zero or null while declaring, if we dont assign any
values to array.

Example for C Arrays:


int a[10];
// integer array
char b[10]; // character array i.e. string

Types of C arrays:
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi dimensional array
1. Two dimensional array
2. Three dimensional array, four dimensional array etc
1. One dimensional array in C:
Syntax : data-type arr_name[array_size];
Array declaration
Syntax: data_type arr_name
[arr_size];
int age [5];

Array initialization
data_type arr_name [arr_size]=(value1, value2, value3,.);

arr_name[ind

int age[5]={0, 1, 2, 3, 4};

age[0];_/*0_i
*/

char str[10]={H,a,i}; (or)char str[0] = H;char str[1] =


a;
char str[10];

str[0];_/*H is
char str[2] = i;

Example program for one dimensional array in C:


#include<stdio.h>int main(){
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf(value of arr[%d] is %d \n, i, arr[i]);
}
}

Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
2. Two dimensional array in C:
Two dimensional array is nothing but array of array.
syntax : data_type array_name[num_of_rows][num_of_column]
S.no
1

Array declaration
Syntax: data_type arr_name [num_of_rows]
[num_of_column];

Example:int arr[2][2];

Array initialization

data_type arr_name[2][2] = {{0,0},{0,1},{1,0}

int arr[2][2] = {1,2, 3, 4};

Example program for two dimensional array in C:


#include<stdio.h>int main(){
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf(value of arr[%d] [%d] : %d\n,i,j,arr[i][j]);
}
}
}

Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
C Strings are nothing but array of characters ended with null character (\0).
This null character indicates the end of the string.
Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes
in C.
Example for C string:
char string[20] = { f , r , e , s , h , 2 , r , e , f , r , e , s , h , \0}; (or)
char string[20] = fresh2refresh; (or)
char string [] = fresh2refresh;
Difference between above declarations are, when we declare char as string[20], 20 bytes of
memory space is allocated for holding the string value.
When we declare char as string[], memory space will be allocated as per the requirement
during execution of the program.
Example program for C string:
#include <stdio.h>
int main ()
{
char string[20] = "fresh2refresh.com";
printf("The string is : %s \n", string );
return 0;
}

Output:
The string is : fresh2refresh.com
C String functions:
String.h header file supports all the string functions in C language. All the string functions are
given below.
Click on each string function name below for detail description and example programs.
S.no
1
2
3
4

String functions
strcat ( )
strncat ( )
strcpy ( )
strncpy ( )

Description
Concatenates str2 at the end of str1.
appends a portion of string to another
Copies str2 into str1
copies given number of characters of one string to another

5
6

strlen ( )
strcmp ( )

strcmpi_(.)

8
9
10
11
12
13
14
15
16
17
18

strchr ( )
strrchr ( )
strstr ( )
strrstr ( )
strdup ( )
strlwr ( )
strupr ( )
strrev ( )
strset ( )
strnset ( )
strtok ( )

gives the length of str1.


Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2.
Same as strcmp() function. But, this function negotiates case. A and a are treated as
same.
Returns pointer to first occurrence of char in str1.
last occurrence of given character in a string is found
Returns pointer to first occurrence of str2 in str1.
Returns pointer to last occurrence of str2 in str1.
duplicates the string
converts string to lowercase
converts string to uppercase
reverses the given string
sets all character in a string to given character
It sets the portion of characters in a string to given character
tokenizing given string using delimi

C Pointer is a variable that stores/points the address of another variable. C Pointer is used to allocate
memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type
such as int, float, char, double, short etc.
Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that p is pointer variable and not a normal variable.
Key points to remember about pointers in C:

Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.

& symbol is used to get the address of the variable.


* symbol is used to get the value of the variable that the pointer is pointing to.
If pointer is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two
pointers.

But, Pointer addition, multiplication, division are not allowed.


The size of any pointer is 2 byte (for 16 bit compiler).

Example program for pointer in C:


#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display qs value using ptr variable */
printf(%d, *ptr);
return 0;
}
Output:

50
C functions are basic building blocks in a program. All C programs are written using functions to
improve re-usability, understandability and to keep track on them. You can learn below concepts of C
functions in this section in detail.
1. What is C function?
2. Uses of C functions
3. C function declaration, function call and definition with example program
4. How to call C functions in a program?
1. Call by value
2. Call by reference
5. C function arguments and return values
1. C function with arguments and with return value
2. C function with arguments and without return value
3. C function without arguments and without return value
4. C function without arguments and with return value
6. Types of C functions
1. Library functions in C
2. User defined functions in C
1. Creating/Adding user defined function in C library
7. Command line arguments in C
8. Variable length arguments in C
1. What is C function?
A large C program is divided into basic building blocks called C function. C function contains set of
instructions enclosed by { } which performs specific operation in a C program. Actually, Collection
of these functions creates a C program.
2. Uses of C functions:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.

We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C programs.
3. C function declaration, function call and function definition:
There are 3 aspects in each C function. They are,
Function declaration or prototype - This informs compiler about the function name, function
parameters and return values data type.
Function call This calls the actual function
Function definition This contains all the statements to be executed.
S.no C function aspects
1
2
3

syntax
return_type function_name ( arguments
function definition list )
{ Body of function; }
function call
function_name ( arguments list );
function
return_type function_name ( argument list );
declaration

Simple example program for C function:


As you know, functions should be declared and defined before calling in a C program.
In the below program, function square is called from main function.
The value of m is passed as argument to the function square. This value is multiplied by
itself in this function and multiplied value p is returned to main function from function
square.
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x )
{
float p ;
p = x * x ;
return ( p ) ;
}

// function definition

Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000
4. How to call C functions in a program?
There are two ways that a C function can be called from a program. They are,
1. Call by value
2. Call by reference
1. Call by value:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
Actual parameter This is the argument which is used in function call.
Formal parameter This is the argument which is used in function definition
Example program for C function (using call by value):
In this program, the values of the variables m and n are passed to the function swap.
These values are copied to formal parameters a and b in swap function and used.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}

Output:
values before swap m = 22
and n = 44

values after swap m = 44


and n = 22
2. Call by reference:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
Example program for C function (using call by reference):

In this program, the address of the variables m and n are passed to the function swap.
These values are not copied to formal parameters a and b in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

Output:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22
All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example C
programs for each one of the below.
1. C function with arguments (parameters) and with return value

2. C function with arguments (parameters) and without return value


3. C function without arguments (parameters) and without return value
4. C function without arguments (parameters) and with return value
S.no

C function

syntax
int function ( int );
// function
declaration
with arguments and with
function ( a );
// function call
return values
int function( int a )
// function definition
{statements; return a;}
void function ( int ); // function declaration
with arguments and without
function( a );
// function call
return values
void function( int a ) // function definition
{statements;}
void function();
// function
declaration
without arguments and without
function();
// function call
return values
void function()
// function definition
{statements;}
int function ( );
// function declaration
without arguments and with
function ( );
// function call
return values
int function( )
// function definition
{statements; return a;}

Note:
If the return data type of a function is void, then, it cant return any values to the calling
function.
If the return data type of the function is other than void such as int, float, double etc, then, it
can return values to the calling function.
1. Example program for with arguments & with return value:
In this program, integer, array and string are passed as arguments to the function. The return type of
this function is int and value of the variable a is returned from the function. The values for array
and string are modified inside the function itself.
#include<stdio.h>
#include<string.h>
int function(int, int[], char[]);
int main()
{
int i, a = 20;
int arr[5] = {10,20,30,40,50};
char str[30] = "\"fresh2refresh\"";
printf("
***values before modification***\n");
printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{

// Accessing each variable


printf("value of arr[%d] is %d\n",i,arr[i]);

}
printf("value of str is %s\n",str);
printf("\n

***values after modification***\n");

a= function(a, &arr[0], &str[0]);


printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("value of str is %s\n",str);
return 0;
}
int function(int a, int *arr, char *str)
{
int i;
a = a+20;
arr[0] = arr[0]+50;
arr[1] = arr[1]+50;
arr[2] = arr[2]+50;
arr[3] = arr[3]+50;
arr[4] = arr[4]+50;
strcpy(str,"\"modified string\"");
return a;
}

Output:
***values before modification***
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
value of str is fresh2refresh***values after
modification***
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100

value of str is modified string


2. Example program for with arguments & without return value:
In this program, integer, array and string are passed as arguments to the function. The return type of
this function is void and no values can be returned from the function. All the values of integer, array
and string are manipulated and displayed inside the function itself.
#include<stdio.h>
void function(int, int[], char[]);
int main()
{
int a = 20;
int arr[5] = {10,20,30,40,50};
char str[30] = "\"fresh2refresh\"";

function(a, &arr[0], &str[0]);


return 0;

void function(int a, int *arr, char *str)


{
int i;
printf("value of a is %d\n\n",a);

for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("\nvalue of str is %s\n",str);

Output:
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
value of str is fresh2refresh
3. Example program for without arguments & without return value:
In this program, no values are passed to the function test and no values are returned from this
function to main function.
#include<stdio.h>

void test();
int main()
{
test();
return 0;
}
void test()
{
int a = 50, b = 80;
printf("\nvalues : a = %d and b = %d", a, b);
}

Output:
values : a = 50 and b = 80
4. Example program for without arguments & with return value:
In this program, no arguments are passed to the function sum. But, values are returned from this
function to main function. Values of the variable a and b are summed up in the function sum and the
sum of these value is returned to the main function.
#include<stdio.h>
int sum();
int main()
{
int addition;
addition = sum();
printf("\nSum of two given values = %d", addition);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = a + b;
return sum;
}

Output:
Sum of two given values = 130
Do you know how many values can be return from C functions?
Always, Only one value can be returned from a function.
If you try to return more than one values from a function, only one value will be returned that
appears at the right most place of the return statement.

For example, if you use return a,b,c in your function, value for c only will be returned and
values a, b wont be returned to the program.
In case, if you want to return more than one values, pointers can be used to directly change the
values in address instead of returning those values to the function.
Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using #include<file_name.h> command
to make use of the functions those are declared in the header files.
When we include header files in our C program using #include<filename.h> command, all C
code of the header files are included in C program. Then, this C program is compiled by
compiler and executed.
Please check the below links for actual C source code for the respective C header files.
1. C stdio.h source code
2. C conio.h source code
3. C string.h source code
4. C stdlib.h source code
5. C math.h source code
6. C time.h source code
7. C ctype.h source code
If you want to check source code for all header files, you can check inside include directory
after C compiler is installed in your machine.
For example, if you install DevC++ compiler in C directory in your machine, C:\DevCpp\include is the path where all header files will be available.
List of most used header files in C:
Check the below table to know all the C library functions and header files in which they are
declared.
Click on the each header file name below to know the list of inbuilt functions declared inside
them.

S.No Header file Description


This is standard input/output header file in which
1 stdio.h
Input/Output
functions are declared
2 conio.h
This is console input/output header file
3 string.h
All string related functions are defined in this header file
This header file contains general functions used in C
4 stdlib.h
programs
5 math.h
All maths related functions are defined in this header file
6 time.h
This header file contains time and clock related functions
7 ctype.h
All character handling functions are defined in this header file
8 stdarg.h Variable argument functions are declared in this header file
9 signal.h
Signal handling functions are declared in this file
10 setjmp.h This file contains all jump functions
11 locale.h
This file contains locale functions
12 errno.h
Error handling functions are given in this file
13 assert.h
This contains diagnostics functions

User defined functions in C:


As you know, there are 2 types of functions in C. They are, library functions and user defined
functions.
Library functions are inbuilt functions which are available in common place called C library.
Where as, User defined functions are the functions which are written by us for our own
requirement.
Adding user defined functions in C library:
Do you know that we can add our own user defined functions in C library?
Yes. It is possible to add, delete, modify and access our own user defined function to or from C
library.
The advantage of adding user defined function in C library is, this function will be available for
all C programs once added to the C library.
We can use this function in any C program as we use other C library functions.
In latest version of GCC compilers, compilation time can be saved since these functions are
available in library in the compiled form.
Normal header files are saved as file_name.h in which all library functions are available.
These header files contain source code and this source code is added in main C program file
where we add this header file using #include <file_name.h> command.
Where as, precompiled version of header files are saved as file_name.gch.

Steps for adding our own functions in C library:


Step 1:
For example, below is a sample function that is going to be added in the C library. Write the
below function in a file and save it as addition.c
addition(int i, int j)
{
int total;
total = i + j;
return total;
}
Step 2:
Compile addition.c file by using Alt + F9 keys (in turbo C).
step 3:
addition.obj file would be created which is the compiled form of addition.c file.
Step 4:
Use the below command to add this function to library (in turbo C).
c:\> tlib math.lib + c:\ addition.obj
+ means adding c:\addition.obj file in the math library.
We can delete this file using (minus).
Step 5:
Create a file addition.h & declare prototype of addition() function like below.
int addition (int i, int j);
Now addition.h file containing prototype of function addition.
Note : Please create, compile and add files in the respective directory as directory name may change for
each IDE.
Step 6:
Let us see how to use our newly added library function in a C program.
# include <stdio.h>
// Including our user defined function.
# include c:\\addition.h
int main ()
{
int total;
// calling function from library
total = addition (10, 20);
printf ("Total = %d \n", total);
}

Output:
Total = 30

ommand line arguments in C:


main() function of a C program accepts arguments from command line or from other shell scripts
by following commands. They are,
argc
argv[]
where,
argc
- Number of arguments in the command line including program name
argv[] This is carrying all the arguments
In real time application, it will happen to pass arguments to the main program itself. These
arguments are passed to the main () function while executing binary file from command line.
For example, when we compile a program (test.c), we get executable file in the name test.
Now, we run the executable test along with 4 arguments in command line like below.
./test this is a program
Where,
argc
argv[0]
argv[1]
argv[2]
argv[3]
argv[4]
argv[5]

=
=
=
=
=
=
=

5
test
this
is
a
program
NULL

Example program for argc() and argv() functions in C:


#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
// command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \
"not equal to 5");
return 1;
}
printf("\n Program
printf("1st arg :
printf("2nd arg :
printf("3rd arg :
printf("4th arg :
printf("5th arg :

name :
%s \n",
%s \n",
%s \n",
%s \n",
%s \n",

%s \n", argv[0]);
argv[1]);
argv[2]);
argv[3]);
argv[4]);
argv[5]);

return 0;
}

Output:
Program name : test
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
Variable length arguments is an advanced concept in C language offered by c99 standard. In c89
standard, fixed arguments only can be passed to the functions.
When a function gets number of arguments that changes at run time, we can go for variable
length arguments.
It is denoted as (3 dots)
stdarg.h header file should be included to make use of variable length argument functions.
Example program for variable length arguments in C:
#include <stdio.h>
#include <stdarg.h>
int add(int num,...);
int main()
{
printf("The value from first function call = " \
"%d\n", add(2,2,3));
printf("The value from second function call= " \
"%d \n", add(4,2,3,4,5));
/*Note - In function add(2,2,3),
first 2 is total number of arguments
2,3 are variable length arguments
In function add(4,2,3,4,5),
4 is total number of arguments
2,3,4,5 are variable length arguments
*/
return 0;
}
int add(int num,...)
{
va_list valist;
int sum = 0;
int i;
va_start(valist, num);
for (i = 0; i < num; i++)
{

sum += va_arg(valist, int);


}
va_end(valist);
return sum;

Output:
The value from first function call = 5
The value from second function call= 14
In the above program, function add is called twice. But, number of arguments passed to the
function gets varies for each. So, 3 dots () are mentioned for function add that indicates that this
function will get any number of arguments at run time.
As you know, C functions are basic building blocks in every C program. We have given key points
those to be kept in mind for using existing C library functions and writing our own functions in a C
program efficiently.
Key points to remember while writing functions in C:

All C programs contain main() function which is mandatory.


main() function is the function from where every C program is started to execute.
Name of the function is unique in a C program.
C Functions can be invoked from anywhere within a C program.
There can any number of functions be created in a program. There is no limit on this.

There is no limit in calling C functions in a program.


All functions are called in sequence manner specified in main() function.
One function can be called within another function.
C functions can be called with or without arguments/parameters. These arguments are nothing
but inputs to the functions.
C functions may or may not return values to calling functions. These values are nothing but
output of the functions.

When a function completes its task, program control is returned to the function from where it is
called.
There can be functions within functions.
Before calling and defining a function, we have to declare function prototype in order to inform
the compiler about the function name, function parameters and return value type.
C function can return only one value to the calling function.
When return data type of a function is void, then, it wont return any values
When return data type of a function is other than void such as int, float, double, it returns
value to the calling function.
main() program comes to an end when there is no functions or commands to execute.
There are 2 types of functions in C. They are, 1. Library functions 2. User defined functions
There are many inbuilt C functions which are offered by C compiler. You can check list of all C
functions and simple example programs with outputs below.

1. C Arithmetic functions
2. C Int, char validation functions
3. C Buffer manipulation function
4. C Time related functions
5. C Dynamic memory allocation
6. C Miscellaneous functions

C functions which are used to perform mathematical operations in a program are called
Arithmetic functions.
Example program for abs(), floor(), round(), ceil(), sqrt(), exp(), log(), sin(), cos(), tan(), pow()
and trunc() functions are given below.
If you want to know what is the structure and declaration of a C function, Please refer
C_Function topic in this tutorial.
List of inbuilt arithmetic functions in C language:
math.h and stdlib.h header files support all the arithmetic functions in C language. All the
arithmetic functions used in C language are given below.
Click on each function name below for detail description and example programs.

S.no Function Description


1 abs ( )
This function returns the absolute value of an integer. The absolute value of a number is always pos
2 floor ( ) This function returns the nearest integer which is less than or equal to the argument passed to this fu
This function returns the nearest integer value of the float/double/long double argument passed to
3 round.(.)
argument. If decimal value is from .6 to .9, it returns the integer value greater than the argument.
4 ceil ( )
This function returns nearest integer value which is greater than or equal to the argument passed to
5 sin ( )
This function is used to calculate sine value.
6 cos ( )
This function is used to calculate cosine.
7 cosh ( ) This function is used to calculate hyperbolic cosine.
8 exp ( )
This function is used to calculate the exponential e to the xth power.
9 tan ( )
This function is used to calculate tangent.
10 tanh ( ) This function is used to calculate hyperbolic tangent.
11 sinh ( ) This function is used to calculate hyperbolic sine.
12 log ( )
This function is used to calculates natural logarithm.
13 log10 ( ) This function is used to calculates base 10 logarithm.
14 sqrt ( ) This function is used to find square root of the argument passed to this function.
15 pow ( ) This is used to find the power of the given number.

16 trunc.(.) This function truncates the decimal value from floating point value and returns integer value.

There are many inbuilt functions in C language which are used to validate the
data type of given variable and to convert upper to lower case and lower to upper
case are given below with description and simple example programs.
List of inbuilt int, char validation functions in C language:
ctype.h header file support all the below functions in C language. Click on each function
name below for detail description and example programs.
S.no

Function

isalpha()
isdigit()
isalnum()
isspace()
islower()
isupper()
isxdigit()
iscntrl()
isprint()
ispunct()
isgraph()
tolower()
toupper()

2
3
4
5
6
7
8
9
10
11
12
13

Description
checks whether character is alphabetic
checks whether character is digit
checks whether character is alphanumeric
checks whether character is space
checks whether character is lower case
checks whether character is upper case
checks whether character is hexadecimal
checks whether character is a control character
checks whether character is a printable character
checks whether character is a punctuation
checks whether character is a graphical character
checks whether character is alphabetic & converts to lower case
checks whether character is alphabetic & converts to upper case

Buffer manipulation functions in C work on the address of the memory block rather than the values
inside the address.
Example programs for memset(), memcpy(), memmove(), memcmp(), memicmp() and
memchr() functions are given below.
S.no Function
1 memset()
2 memcpy()
3
4
5
6

Description
It is used to initialize a specified number of bytes to null or any other value in the buffer
It is used to copy a specified number of bytes from one memory to another
It is used to copy a specified number of bytes from one memory to another
memmove() Difference between memmove and memcpy is, overlap can happen on memmove whereas me
way
memcmp() It is used to compare specified number of characters from two buffers
memicmp() It is used to compare specified number of characters from two buffers regardless of the case of th
memchr() It is used to locate the first occurrence of the character in the specified string

Example program for memset() function in C:


memset( ) function is used to initialize specified number of bytes to null or to any other value in
the buffer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int i;
/* allocate memory for array of 5 elements */
char *a = (char *) malloc(5*sizeof(char));
printf("Values before memset\n");
for (i = 0; i < 5; ++i)
printf(" a[%d] = %d ,", i,
a[i]);

/* All elements are set to 3. It can be set to any value */


memset(a, 3, 5*sizeof(char));
printf("\nValues after memset\n");
for (i = 0; i < 5; ++i)
printf(" a[%d] = %d ,", i,
a[i]);
// remove x from memory
free(a);
return 0;

Output:
Values before memset
a[0] = 0 , a[1] = 0 , a[2] = 0 , a[3] = 0 , a[4] = 0
Values after memset
a[0] = 3 , a[1] = 3 , a[2] = 3 , a[3] = 3 , a[4] = 3
Example program for memcpy() function in C:
memcpy( ) function is used to copy a specified number of bytes from one memory to another.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] ;
if (memcpy(str2,str1, strlen(str1)))
{
printf("Elements in str1 are copied to str2 .\n");
printf("str1 = %s\n str2 = %s \n", str1, str2);
}
else
printf("Error while coping str1 into str2.\n");
return 0;
}

Output:
Elements in str1 are copied to str2 .
str1 = fresh
str2 = fresh
Example program for memmove() function in C:
memmove( ) function is used to copy a specified number of bytes from one memory to another
or to overlap on same memory.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
printf("str1 before memmove\n");
printf("str1 = %s\n ", str1);
if (memmove(str1+2,str1, strlen(str1)))
{
printf("Elements in str1 are moved/overlapped on str1.\n");
printf("str1 = %s \n", str1);
}
else
printf("Error while coping str1 into str2.\n");
return 0;
}

Output:
str1 before memmove
str1 = fresh
Elements in str1 are moved/overlapped on str1 .
str1 = frfresh
Example program for memcmp() function in C:
memcmp( ) function is used to compare specified number of characters from two buffers.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] = "refresh";
if (!memcmp(str1,str2, 5*sizeof(char)))
printf("Elements in str1 and str2 are same.\n");
else
printf("Elements in str1 and str2 are not same.\n");
return 0;
}

Output:
Elements in str1 and str2 are not same.
Example program for memicmp() function in C:
memicmp( ) function is used to compare specified number of characters from two buffers
regardless of the case of the characters.
If we use memcmp() function instead of memicmp, the output of the below program will be
Elements in str1 and str2 are not same.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] = "FRESH";
if (!memicmp(str1,str2, 5*sizeof(char)))
printf("Elements in str1 and str2 are same.\n");
else
printf("Elements in str1 and str2 are not same.\n");
return 0;
}

Output:
Elements in str1 and str2 are same.
Example program for memchr() function in C:
memchr( ) function is used to locate the first occurrence of the character in the specified string.
#include <stdio.h>
#include <string.h>
int main ()
{
char *ptr;
char string[] = "fresh2refresh";
ptr = (char *) memchr (string, 'h', strlen(string));
if (ptr != NULL)
printf ("character 'h' is found at " \
"position %d.\n", ptr-string+1);
else
printf ("character 'h' is not found.\n");
return 0;
}

Output:
character h is found at position 5.

Time functions in C are used to interact with system time routine and formatted time outputs are
displayed. Example programs for the time functions are given below.
S.no
1
2
3
4
5
6
7
8
9
10

Function Description
setdate() This function used to modify the system date
getdate() This function is used to get the CPU time
clock()
This function is used to get current system time
time()
This function is used to get current system time as structure
difftime() This function is used to get the difference between two given times
strftime() This function is used to modify the actual time format
mktime() This function interprets tm structure as calendar time
localtime() This function shares the tm structure that contains date and time informations
gmtime() This function shares the tm structure that contains date and time informations
ctime()
This function is used to return string that contains date and time informations
Tm structure contents are interpreted by this function as calendar time. This time is converted
11 asctime()
string.

Example program for setdate() function in C:


This function is used to modify the system date. Please note that other C compilers may not support
this setdate() function except turbo C.
#include<stdio.h>
#include<dos.h>
#include<conio.h>
int main()
{
struct date dt;
printf("Enter new date in the format(day month year)");
scanf("%d%d%d",&dt.da_day,&dt.da_mon,&dt.da_year);
setdate(&dt);
printf("Now, current system date is %d-%d-%d\n"
,dt.da_day,dt.da_mon,dt.da_year);
return 0;
}

Output:
Enter new date in the format (day month year)
01 12 2012
Now, current system date is 01-12-2012
Example program for getdate() function in C:
This function is used to get the CPU time. Please note that other C compilers may not support this
getdate() function except turbo C.
#include<stdio.h>

#include<dos.h>
int main()
{
struct date dt;
getdate(&dt);
printf("Operating system's current date is %d-%d-%d\n"
,dt.da_day,dt.da_mon,dt.da_year);
return 0;
}

Output:
Operating systems current date is 12-012012
Example program for clock() function in C:
This function is used to get current system time
#include <stdio.h>
#include <time.h>
#include <math.h>
int main()
{
int i;
clock_t CPU_time_1 = clock();
printf("CPU start time is : %d \n", CPU_time_1);
for(i = 0; i < 150000000; i++);
clock_t CPU_time_2 = clock();
printf("CPU end time is : %d", CPU_time_2);
}

Output:
CPU start time is : 0
CPU end time is : 380000
Example program for time() function in C:
This function is used to get current system time as structure
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);

printf ("Number of hours since 1970 Jan 1st " \


"is %ld \n", seconds/3600);
return 0;

Output:
Number of hours since 1970 Jan 1st is 374528
Example program for difftime() function in C:
This function is used to get the difference between two given times
#include <stdio.h>
#include <time.h>
int main()
{
time_t begin,end;
long i;
begin= time(NULL);
for(i = 0; i < 150000000; i++);
end = time(NULL);
printf("for loop used %f seconds to complete the " \
"execution\n", difftime(end, begin));
return 0;
}

Output:
for loop used 15.000000 seconds to complete the execution
Example program for strftime(), asctime() and localtime() in C:
strftime() - This function is used to modify the actual time format.
asctime() tm structure contents are interpreted by asctime() function as calendar time. This
time is converted into string.
localtime() This function shares the tm structure that contains date and time informations.
#include <stdio.h>
#include <time.h>
#define LEN 150
int main ()
{
char buf[LEN];
time_t curtime;
struct tm *loc_time;
//Getting current time of system
curtime = time (NULL);
// Converting current time to local time
loc_time = localtime (&curtime);
// Displaying date and time in standard format
printf("%s", asctime (loc_time));
strftime (buf, LEN, "Today is %A, %b %d.\n", loc_time);
fputs (buf, stdout);
strftime (buf, LEN, "Time is %I:%M %p.\n", loc_time);
fputs (buf, stdout);

return 0;
}

Output:
Sat Sep 22 01:15:03 2012
Today is Saturday, Sep 22.
Time is 01:15 AM.
Example program for mktime() and ctime() functions in C:
mktime() function interprets tm structure as calendar time.
ctime() function is used to return string that contains date and time informations.
#include <stdio.h>
#include <time.h>
int main()
{
struct tm strtime;
time_t timeoftheday;
strtime.tm_year = 2008-1900;
strtime.tm_mon = 1;
strtime.tm_mday = 4;
strtime.tm_hour = 02;
strtime.tm_min = 30;
strtime.tm_sec = 38;
strtime.tm_isdst = 0;
timeoftheday = mktime(&strtime);
printf(ctime(&timeoftheday));
return 0;
}

Output:
Mon Feb 4 02:30:38 2008
Example program for gmtime() function in C:
This function shares the tm structure that contains date and time informations.
#include <stdio.h>
#include <time.h>
int main()
{
time_t orig_format;
time(&orig_format);
printf ("Universal Time is %s",

asctime(gmtime(&orig_format)));
return 0;
}

Output:
Universal Time is Sat Sep 22 08:11:40 2012

Dynamic memory allocation in C:


The process of allocating memory during program execution is called dynamic memory allocation.
Dynamic memory allocation functions in C:
C language offers 4 dynamic memory allocation functions. They are,
1.
2.
3.
4.

malloc()
calloc()
realloc()
free()

S.no Function
Syntax
1 malloc () malloc (number *sizeof(int));
2 calloc () calloc (number, sizeof(int));
realloc (pointer_name, number *
3 realloc ()
sizeof(int));
4 free ()
free (pointer_name);
1. malloc() function in C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldnt able to allocate requested amount of
memory.
Example program for malloc() function in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{

printf("Couldn't able to allocate requested memory\n");


}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}

Output:
Dynamically allocated memory content :
fresh2refresh.com
2. calloc() function in C:
calloc () function is also like malloc () function. But calloc () initializes the allocated memory to
zero. But, malloc() doesnt.
Example program for calloc() function in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content
: " \
"%s\n", mem_allocation );
free(mem_allocation);
}

Output:
Dynamically allocated memory content :
fresh2refresh.com
3. realloc() function in C:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to
new size.

If enough space doesnt exist in memory of current block to extend, new block is allocated for
the full size of reallocation, then copies the existing data to new block and then frees the old
block.
4. free() function in C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and
returns the memory to the system.
Example program for realloc() and free() functions in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
mem_allocation=realloc(mem_allocation,100*sizeof(char));
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"space is extended upto " \
"100 characters");
}
printf("Resized memory : %s\n", mem_allocation );
free(mem_allocation);
}

Output:
Dynamically allocated memory content :
fresh2refresh.com
Resized memory : space is extended upto 100 characters
Difference between static memory allocation and dynamic memory allocation in C:

S.no
Static memory allocation
1 In static memory allocation, memory is allocated while writing the C program. Actually, user requested memo

will be allocated at compile time.


Memory size cant be modified while execution.
Example: array

Difference between malloc() and calloc() functions in C:

S.no
malloc()
1 It allocates only single block of requested memory
It allocates multiple blo
int *ptr;ptr = malloc( 20 * sizeof(int) );For the above, 20*4 bytes of memory only int *ptr;Ptr = calloc( 2
2 allocated
in
one
block. contains
Total = 80 bytes
Total = 1600 bytes
3 malloc () doesnt initializes the allocated memory. It contains garbage values
calloc () initializes the
type cast must be done since this function returns void pointer int *ptr;ptr =
4
Same as malloc () func
(int*)malloc(sizeof(int)*20 );

Typecasting concept in C language is used to modify a variable from one date type to another data
type. New data type should be mentioned before the variable name or value in brackets which to be
typecast.
C type casting example program:
In the below C program, 7/5 alone will produce integer value as 1.
So, type cast is done before division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf("%f",x);
}

Output:
1.400000
Note:
It is best practice to convert lower data type to higher data type to avoid data loss.
Data will be truncated when higher data type is converted to lower. For example, if float is
converted to int, data which is present after decimal point will be lost.
Inbuilt typecast functions in C:
There are many inbuilt typecasting functions available in C language which performs data type
conversion from one type to another.
Click on each function name below for description and example programs.
S.no Typecast function

Description

1
2
3
4
5

atof()
atoi()
atol()
itoa()
ltoa()

Converts string to float


Converts string to int
Converts string to long
Converts int to string
Converts long to string

Descriptions and example programs for C environment functions such as getenv(), setenv(), putenv()
and other functions perror(), random() and delay() are given below.
S.no

Function

Description

getenv()

This function gets the current value of the environment variable

setenv()

This function sets the value for environment variable

putenv()

This function modifies the value for environment variable

perror()

Displays most recent error that happened during library function call

rand()

Returns random integer number range from 0 to at least 32767

delay()

Suspends the execution of the program for particular time

Example program for getenv() function in C:


This function gets the current value of the environment variable.
Let us assume that environment variable DIR is assigned to /usr/bin/test/. Below program will
show you how to get this value using getenv() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Directory = %s\n", getenv("DIR"));
return 0;
}

Output:
/usr/bin/test/
Example program for setenv() function in C:
This function sets the value for environment variable.
Let us assume that environment variable FILE is to be assigned /usr/bin/example.c. Below
program will show you how to set this value using setenv() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("FILE","/usr/bin/example.c",50);
printf("File = %s\n", getenv("FILE"));
return 0;

Output:
File = /usr/bin/example.c
Example program for putenv() function in C:
This function modifies the value of environment variable.
Below example program shows that how to modify an existing environment variable value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
setenv("DIR","/usr/bin/example/",50);
printf("Directory name before modifying = " \
"%s\n", getenv("DIR"));

putenv("DIR=/usr/home/");
printf("Directory name after modifying = " \
"%s\n", getenv("DIR"));
return 0;

Output:
Directory name before modifying =
/usr/bin/example/
Directory name after modifying = /usr/home/
Example program for perror() function in C:
This function displays most recent error that happened during library function call.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char filename[40] = "test.txt";
/*

Let us consider test.txt not available

*/

fp = f open(filename, "r");
if(fp == NULL)
{
perror("File not found");
printf("errno : %d.\n", errno);
return 1;
}
printf("File is found and opened for reading");

fclose(fp);
return 0;

Output:
errno : 22.
File not found: No such file or directory
Example program for rand() function in C:
This function returns the random integer numbers range from 0 upto 32767
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main ()
{
printf ("1st random number : %d\n", rand() % 100);
printf ("2nd random number : %d\n", rand() % 100);
printf ("3rd random number: %d\n", rand());
return 0;
}

Output:
1st random number : 83
2nd random number : 86
3rd random number: 16816927
Example program for delay() function in C:
This function suspends the execution of the program for particular time.
#include<stdio.h>
#include<stdlib.h>
int main ()
{
printf("Suspends the execution of the program " \
"for particular time");
delay(5000);
return 0;
}

// 5000 mille seconds

Output:
Suspends the execution of the program for particular
time
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be allocated for
each separately.
It is a best practice to initialize a structure to null while declaring, if we dont assign any values
to structure members.
Difference between C variable, C array and C structure:

A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types
Data types can be int, char, float, double and long double etc.

Datatype

C variable

C array

Syntax Example Syntax


int
char

int a

a = 20

char b b=Z

Example
a[0] = 10
a[1] = 20
int a[3]
a[2] = 30
a[3] = \0
char b[10] b=Hello

C structure
Syntax
Example
struct student
{
a = 10
int a;
b = Hello
char b[10];
}

Below table explains following concepts in C structure.


1. How to declare a C structure?
2. How to initialize a C structure?
3. How to access the members of a C structure?
Type

Syntax

Example

Using normal variable


struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
struct student
{
int mark;
char name[10];
float average;
};

Using pointer variabe


struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
struct student
{
int mark;
char name[10];
float average;
};

Declaring structure variable struct student report;


struct student report = {100, Mani,
Initializing structure variable
99.5};
report.mark
Accessing
report.name
structure members
report.average

struct student *report, rep;


struct student rep = {100, Mani, 99.5};
report = &rep;
report -> mark
report -> name
report -> average

Example program for C structure:


This program is used to store and access id, name and percentage for one student. We can also
store and access these data for many students using array of structures. You can check C Array of
Structures to know how to store and access these data for many students.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{

struct student record = {0}; //Initializing to null


record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example program Another way of declaring C structure:
In this program, structure variable record is declared while declaring structure itself. In above
structure example program, structure variable struct student record is declared inside main function
which is after declaring structure.
#include <stdio.h>
#include <string.h>
struct student
{
int id;

} record;

char name[20];
float percentage;

int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
C structure declaration in separate header file:
In above structure programs, C structure is declared in main source file. Instead of declaring C
structure in main source file, we can have this structure declaration in another file called header file
and we can include that header file in main source file as shown below.
Header file name structure.h
Before compiling and executing below C program, create a file named structure.h and declare the
below structure.
struct student
{
int id;
char name[20];
float percentage;
} record;
Main file name structure.c:
In this program, above created header file is included in structure.c source file as #include
Structure.h. So, the structure declared in structure.h file can be used in structure.c source file.
// File name - structure.c
#include <stdio.h>
#include <string.h>
#include "structure.h"
/* header file where C structure is
declared */
int main()
{

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Uses of C structures:
1.
2.
3.
4.
5.
6.

C Structures can be used to store huge data. Structures act as a database.


C Structures can be used to send data to the printer.
C Structures can interact with keyboard and mouse to store the data.
C Structures can be used in drawing and floppy formatting.
C Structures can be used to clear output screen contents.
C Structures can be used to check computers memory size etc.

Continue on C Array of Structures.


Continue on C Passing structure to function.
Continue on C Structure using Pointer.
Continue on C Structure within Structure.
Continue on C Structure Memory Allocation.
Continue on C Structure Padding.

C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and memory will be allocated for
each separately.
It is a best practice to initialize a structure to null while declaring, if we dont assign any values
to structure members.

Difference between C variable, C array and C structure:

A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types
Data types can be int, char, float, double and long double etc.

Datatype

C variable

C array

Syntax Example Syntax


int
char

int a

a = 20

char b b=Z

Example
a[0] = 10
a[1] = 20
int a[3]
a[2] = 30
a[3] = \0
char b[10] b=Hello

C structure
Syntax

Example

struct student
{
a = 10
int a;
b = Hello
char b[10];
}

Below table explains following concepts in C structure.


1. How to declare a C structure?
2. How to initialize a C structure?
3. How to access the members of a C structure?
Type

Using normal variable


struct tag_name
{
data type var_name1;
Syntax
data type var_name2;
data type var_name3;
};
struct student
{
int mark;
Example
char name[10];
float average;
};
Declaring structure variable struct student report;
struct student report = {100, Mani,
Initializing structure variable
99.5};
report.mark
Accessing
report.name
structure members
report.average

Using pointer variabe


struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
struct student
{
int mark;
char name[10];
float average;
};
struct student *report, rep;
struct student rep = {100, Mani, 99.5};
report = &rep;
report -> mark
report -> name
report -> average

Example program for C structure:


This program is used to store and access id, name and percentage for one student. We can also
store and access these data for many students using array of structures. You can check C Array of
Structures to know how to store and access these data for many students.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[20];
float percentage;
};
int main()
{

struct student record = {0}; //Initializing to null


record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example program Another way of declaring C structure:
In this program, structure variable record is declared while declaring structure itself. In above
structure example program, structure variable struct student record is declared inside main function
which is after declaring structure.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
} record;
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
C structure declaration in separate header file:
In above structure programs, C structure is declared in main source file. Instead of declaring C
structure in main source file, we can have this structure declaration in another file called header file
and we can include that header file in main source file as shown below.
Header file name structure.h
Before compiling and executing below C program, create a file named structure.h and declare the
below structure.
struct student
{
int id;
char name[20];
float percentage;
} record;
Main file name structure.c:
In this program, above created header file is included in structure.c source file as #include
Structure.h. So, the structure declared in structure.h file can be used in structure.c source file.
// File name - structure.c
#include <stdio.h>
#include <string.h>
#include "structure.h"
/* header file where C structure is
declared */
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000

Uses of C structures:
1.
2.
3.
4.
5.
6.

C Structures can be used to store huge data. Structures act as a database.


C Structures can be used to send data to the printer.
C Structures can interact with keyboard and mouse to store the data.
C Structures can be used in drawing and floppy formatting.
C Structures can be used to clear output screen contents.
C Structures can be used to check computers memory size etc.

As you know, C Structure is collection of different datatypes ( variables ) which are grouped
together. Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.
Example program for array of structures in C:
This program is used to store and access id, name and percentage for 3 students. Structure array is
used in this program to store and display records for many students. You can store n number of
students record by declaring structure variable as struct student record[n], where n can be 1000 or
5000 etc.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf("
Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);

printf(" Percentage is: %f\n\n",record[i].percentage);


}
return 0;
}

Output:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
Example program for declaring many structure variable in C:
In this program, two structure variables record1 and record2 are declared for same structure and
different values are assigned for both structure variables. Separate memory is allocated for both
structure variables to store the data.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2 = {2, "Mani", 93.5};
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", record1.id);
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);
printf("Records of STUDENT2: \n");
printf(" Id is: %d \n", record2.id);
printf(" Name is: %s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);
}

return 0;

Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000

A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only.
It wont be available to other functions unless it is passed to those functions by value or by
address(reference).
Else, we have to declare structure variable as global variable. That means, structure variable
should be declared outside the main function. So, this structure will be visible to all the
functions in a C program.
Passing structure to function in C:
It can be done in below 3 ways.
1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure Declare structure variable as global
Example program passing structure to function in C by value:
In this program, the whole structure is passed to another function by value. It means the whole
structure is passed to another function with all members and their values. So, this structure can be
accessed from called function. This concept is very useful while writing very big programs in C.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");

record.percentage = 86.5;

func(record);
return 0;

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example program Passing structure to function in C by address:
In this program, the whole structure is passed to another function by address. It means only the
address of the structure is passed to another function. The whole structure is not passed to another
function with all members and their values. So, this structure can be accessed from called function by
its address.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{

struct student record;


record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(&record);
return 0;

void func(struct student *record)


{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example program to declare a structure variable as global in C:
Structure variables also can be declared as global variables as we declare other variables in C.
So, When a structure variable is declared as global, then it is visible to all the functions in a program. In
this scenario, we dont need to pass the structure to any function separately.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;

void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
C structure can be accessed in 2 ways in a C program. They are,
1. Using normal structure variable
2. Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to
access the data using pointer variable. You have learnt how to access structure data using normal
variable in C Structure topic. So, we are showing here how to access structure data using pointer

variable in below C program.


Example program for C structure using pointer:
In this program, record1 is normal structure variable and ptr is pointer structure variable. As
you know, Dot(.) operator is used to access the data using normal structure variable and arrow(->) is
used to access data using pointer variable.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
}

return 0;

Output:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Example program to copy a structure in C:
There are many methods to copy one structure to another structure in C.
1. We can copy using direct assignment of one structure to another structure or
2. we can use C inbuilt function memcpy() or
3. we can copy by individual structure members.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];

float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2, *record3, *ptr1, record4;
printf("Records of STUDENT1 - record1 structure \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",
record1.id, record1.name, record1.percentage);
// 1st method to copy whole structure to another structure
record2=record1;
printf("\nRecords of STUDENT1 - Direct copy from " \
"record1 \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",
record2.id, record2.name, record2.percentage);
// 2nd method to copy using memcpy function
ptr1 = &record1;
memcpy(record3, ptr1, sizeof(record1));
printf("\nRecords of STUDENT1 - copied from record1 " \
"using memcpy \n");
printf(" Id : %d \n Name : %s\n Percentage : %f\n",
record3->id, record3->name, record3->percentage);
// 3rd method to copy by individual members
printf("\nRecords of STUDENT1 - Copied individual " \
"members from record1 \n");
record4.id=record1.id;
strcpy(record4.name, record1.name);
record4.percentage = record1.percentage;
printf(" Id : %d \n Name : %s\n Percentage : %f\n",
record4.id, record4.name, record4.percentage);
return 0;
}

Output:
Records of STUDENT1 - record1 structure
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 Direct copy from record1
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 copied from record1 using memcpy
Id : 1

Name : Raju
Percentage : 90.500000
Records of STUDENT1 Copied individual members from record1
Id : 1
Name : Raju
Percentage : 90.500000

Nested structure in C is nothing but structure within structure. One structure can be declared
inside other structure as we declare structure members inside a structure. The structure
variables can be a normal structure variable or a pointer variable to access the data. You can
learn below concepts in this section.
1. Structure within structure in C using normal variable
2. Structure within structure in C using pointer variable
1. Structure within structure in C using normal variable:
This program explains how to use structure within structure in C using normal variable.
student_college_detail structure is declared inside student_detail structure in this program. Both
structure variables are normal structure variables.
Please note that members of student_college_detail structure are accessed by 2 dot(.) operator
and members of student_detail structure are accessed by single dot(.) operator.
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n",
stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);

return 0;
}

Output:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
Structure within structure in C using pointer variable:
This program explains how to use structure within structure in C using pointer variable.
student_college_detail structure is declared inside student_detail structure in this program. one
normal structure variable and one pointer structure variable is used in this program.
Please note that combination of .(dot) and ->(arrow) operators are used to access the structure member
which is declared inside the structure.
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data, *stu_data_ptr;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
stu_data_ptr = &stu_data;
printf(" Id is: %d \n", stu_data_ptr->id);
printf(" Name is: %s \n", stu_data_ptr->name);
printf(" Percentage is: %f \n\n",
stu_data_ptr->percentage);
printf(" College Id is: %d \n",
stu_data_ptr->clg_data.college_id);
printf(" College Name is: %s \n",
stu_data_ptr->clg_data.college_name);
}

return 0;

Output:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University

Do you know how memory is allocated for structure members in C?. You can learn below
concepts of C in this topic.
1. how structure members are stored in memory?
2. What is structure padding?
3. How to avoid structure padding?
1. How structure members are stored in memory?
Always, contiguous(adjacent) memory locations are used to store structure members in memory.
Consider below example to understand how memory is allocated for structures.
Example program for memory allocation in C structure:
#include <stdio.h>
#include <string.h>
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
int main()
{
int i;
struct student record1 = {1, 2, 'A', 'B', 90.5};
printf("size of structure in bytes : %d\n",
sizeof(record1));
printf("\nAddress
printf("\nAddress
printf("\nAddress
printf("\nAddress
printf("\nAddress
return 0;
}

of
of
of
of
of

id1
id2
a
b
percentage

=
=
=
=
=

%u", &record1.id1 );
%u", &record1.id2 );
%u", &record1.a );
%u", &record1.b );
%u",&record1.percentage);

Output:
size of structure in bytes : 16
Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Address of b = 675376777
Address of percentage = 675376780
There are 5 members declared for structure in above program. In 32 bit compiler, 4 bytes of
memory is occupied by int datatype. 1 byte of memory is occupied by char datatype and 4 bytes of
memory is occupied by float datatype.
Please refer below table to know from where to where memory is allocated for each datatype in
contiguous (adjacent) location in memory.
Memory allocation in C (32 bit compiler)
From Address
To Address Total bytes
int id1
675376768
675376771
4
int id2
675376772
675376775
4
char a
675376776
1
char b
675376777
1
Addresses 675376778 and 675376779 are left empty
2
(Do you know why? Please see Structure padding topic below)
float percentage
675376780
675376783
4
The pictorial representation of above structure memory allocation is given below. This diagram
will help you to understand the memory allocation concept in C very easily.
Datatype

In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left
empty) between memory addresses which are allocated for other structure members while
memory allocation. This concept is called structure padding.
Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit

processor) from memory at a time.


To make use of this advantage of processor, data are always aligned as 4 bytes package which
leads to insert empty addresses between other members address.
Because of this structure padding concept in C, size of the structure is always not same as what
we think.
For example, please consider below structure that has 5 members.
..
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
..
As per C concepts, int and float datatypes occupy 4 bytes each and char datatype occupies 1
byte for 32 bit processor. So, only 14 bytes (4+4+1+1+4) should be allocated for above
structure.
But, this is wrong. Do you know why?
Architecture of a computer processor is such a way that it can read 1 word from memory at a
time.
1 word is equal to 4 bytes for 32 bit processor and 8 bytes for 64 bit processor. So, 32 bit
processor always reads 4 bytes at a time and 64 bit processor always reads 8 bytes at a time.
This concept is very useful to increase the processor speed.
To make use of this advantage, memory is arranged as a group of 4 bytes in 32 bit processor and
8 bytes in 64 bit processor.
Below C program is compiled and executed in 32 bit compiler. Please check memory allocated
for structure1 and structure2 in below program.
Example program for structure padding in C:
#include <stdio.h>
#include <string.h>
/*

Below structure1 and structure2 are same.


They differ only in member's allignment */

struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{

int id1;
char name;
int id2;
char c;
float percentage;
};
int main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n",
sizeof(a));
printf ( "\n
Address of id1
= %u", &a.id1 );
printf ( "\n
Address of id2
= %u", &a.id2 );
printf ( "\n
Address of name
= %u", &a.name );
printf ( "\n
Address of c
= %u", &a.c );
printf ( "\n
Address of percentage = %u",
&a.percentage );
printf("

\n\nsize of structure2 in
sizeof(b));
printf ( "\n
Address of id1
printf ( "\n
Address of name
printf ( "\n
Address of id2
printf ( "\n
Address of c
printf ( "\n
Address of percentage
&b.percentage );
getchar();
return 0;
}

Output:
size of structure1 in bytes : 16
Address of id1 = 1297339856
Address of id2 = 1297339860
Address of name = 1297339864
Address of c = 1297339865
Address of percentage = 1297339868
size of structure2 in bytes : 20
Address of id1 = 1297339824
Address of name = 1297339828
Address of id2 = 1297339832
Address of c = 1297339836
Address of percentage = 1297339840

bytes : %d\n",
=
=
=
=
=

%u",
%u",
%u",
%u",
%u",

&b.id1 );
&b.name );
&b.id2 );
&b.c );

Structure padding analysis for above C program:


Memory allocation for structure1:

In above program, memory for structure1 is allocated sequentially for first 4 members.
Whereas, memory for 5th member percentage is not allocated immediate next to the end of
member c.
There are only 2 bytes remaining in the package of 4 bytes after memory allocated to member
c.
Range of this 4 byte package is from 1297339864 to 1297339867.
Addresses 1297339864 and 1297339865 are used for members name and c. Addresses
1297339866 and 1297339867 only is available in this package.
But, member percentage is datatype of float and requires 4 bytes. It cant be stored in the
same memory package as it requires 4 bytes. Only 2 bytes are free in that package.
So, next 4 byte of memory package is chosen to store percentage data which is
from 1297339868 to 1297339871.
Because of this, memory 1297339866 and 1297339867 are not used by the program and those 2
bytes are left empty.
So, size of structure1 is 16 bytes which is 2 bytes extra than what we think. Because, 2 bytes are
left empty.
Memory allocation for structure2:

Memory for structure2 is also allocated as same as above concept. Please note that structure1

and structure2 are same. But, they differ only in the order of the members declared inside the
structure.
4 bytes of memory is allocated for 1st structure member id1 which occupies whole 4 byte of
memory package.
Then, 2nd structure member name occupies only 1 byte of memory in next 4 byte package
and remaining 3 bytes are left empty. Because, 3rd structure member id2 of datatype
integer requires whole 4 byte of memory in the package. But, this is not possible as only 3 bytes
available in the package.
So, next whole 4 byte package is used for structure member id2.
Again, 4th structure member c occupies only 1 byte of memory in next 4 byte package and
remaining 3 bytes are left empty.
Because, 5th structure member percentage of datatype float requires whole 4 byte of memory
in the package.
But, this is also not possible as only 3 bytes available in the package. So, next whole 4 byte
package is used for structure member percentage.
So, size of structure2 is 20 bytes which is 6 bytes extra than what we think. Because, 6 bytes are
left empty.
How to avoid structure padding in C?
#pragma pack ( 1 ) directive can be used for arranging memory for structure members very next
to the end of other structure members.
VC++ supports this feature. But, some compilers such as Turbo C/C++ does not support this
feature.
Please check the below program where there will be no addresses (bytes) left empty because of
structure padding.
Example program to avoid structure padding in C:
#include <stdio.h>
#include <string.h>
/*

Below structure1 and structure2 are same.


They differ only in member's allignment */

#pragma pack(1)
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{
int id1;
char name;
int id2;
char c;
float percentage;

};
int main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n",
sizeof(a));
printf ( "\n
Address of id1
= %u", &a.id1 );
printf ( "\n
Address of id2
= %u", &a.id2 );
printf ( "\n
Address of name
= %u", &a.name );
printf ( "\n
Address of c
= %u", &a.c );
printf ( "\n
Address of percentage = %u",
&a.percentage );
printf("

\n\nsize of structure2 in
sizeof(b));
printf ( "\n
Address of id1
printf ( "\n
Address of name
printf ( "\n
Address of id2
printf ( "\n
Address of c
printf ( "\n
Address of percentage
&b.percentage );
getchar();
return 0;

bytes : %d\n",
=
=
=
=
=

%u",
%u",
%u",
%u",
%u",

&b.id1 );
&b.name );
&b.id2 );
&b.c );

Output:
size of structure1 in bytes : 14
Address of id1 = 3438103088
Address of id2 = 3438103092
Address of name = 3438103096
Address of c = 3438103097
Address of percentage = 3438103098
size of structure2 in bytes : 14
Address of id1 = 3438103072
Address of name = 3438103076
Address of id2 = 3438103077
Address of c = 3438103081
Address of percentage = 3438103082
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C
program. This is same like defining alias for the commands.
Consider the below structure.
struct student
{

int mark [2];


char name [10];
float average;
}
Variable for the above structure can be declared in two ways.
1st way :
struct student record;
struct student *record;

/* for normal variable */


/* for pointer variable */

2nd way :
typedef struct student status;
When we use typedef keyword before struct <tag_name> like above, after that we can simply
use type definition status in the C program to declare structure variable.
Now, structure variable declaration will be, status record.
This is equal to struct student record. Type definition for struct student is status. i.e. status =
struct student
An alternative way for structure declaration using typedef in C:
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
To declare structure variable, we can use the below statements.
status record1;
status record2;

/* record 1 is structure variable */


/* record 2 is structure variable */

Example program for C typedef:


// Structure using typedef:
#include <stdio.h>
#include <string.h>
typedef struct student
{
int id;
char name[20];
float percentage;
} status;
int main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;

Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Typedef can be used to simplify the real commands as per our need.
For example, consider below statement.
typedef long long int LLI;
In above statement, LLI is the type definition for the real C command long long int. We can
use type definition LLI instead of using full command long long int in a C program once it is
defined.
Another example program for C typedef:
#include <stdio.h>
#include <limits.h>
int main()
{
typedef long long int LLI;
printf("Storage size for long long int data " \
"type : %ld \n", sizeof(LLI));
}

return 0;

Output:
Storage size for long long int data type : 8

C Union is also like structure, i.e. collection of different data types which are grouped
together. Each element in a union is called member.
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We cant access all member values at the
same time in union. But, structure can access all member values at the same time. This is
because, Union allocates one common storage space for all its members. Where as Structure

allocates storage space for all its members separately.


Many union variables can be created in a program and memory will be allocated for each union
variable separately.
Below table will help you how to form a C union, declare a union, initializing and accessing the
members of the union.
Type

Using normal variable


union tag_name
{
data type var_name1;
Syntax
data type var_name2;
data type var_name3;
};
union student
{
int mark;
Example
char name[10];
float average;
};
Declaring union variable union student report;
union student report = {100, Mani,
Initializing union variable
99.5};
report.mark
Accessing union members report.name
report.average

Using pointer variable


union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
union student
{
int mark;
char name[10];
float average;
};
union student *report, rep;

union student rep = {100, Mani, 99.5};rep


report -> mark
report -> name
report -> average

Example program for C union:


#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1
printf(" Name
:
printf(" Subject
:
printf(" Percentage :

values example\n");
%s \n", record1.name);
%s \n", record1.subject);
%f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name
: %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject
: %s \n", record2.subject);
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;

Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
Explanation for above C union program:
There are 2 union variables declared in this program to understand the difference in accessing
values of union members.
Record1 union variable:
Raju is assigned to union member record1.name . The memory location name is
record1.name and the value stored in this location is Raju.
Then, Maths is assigned to union member record1.subject. Now, memory location name is
changed to record1.subject with the value Maths (Union can hold only one member at a
time).
Then, 86.50 is assigned to union member record1.percentage. Now, memory location name
is changed to record1.percentage with value 86.50.
Like this, name and value of union member is replaced every time on the common storage
space.
So, we can always access only one union member for which value is assigned at last. We cant
access other member values.
So, only record1.percentage value is displayed in output. record1.name and
record1.percentage are empty.
Record2 union variable:
If we want to access all member values using union, we have to access the member before
assigning values to other members as shown in record2 union variable in this program.
Each union members are accessed in record2 example immediately after assigning values to
them.

If we dont access them before assigning values to other member, member name and value will
be over written by other member as all members are using same memory.
We cant access all members in union at same time but structure can do that.
Example program Another way of declaring C union:
In this program, union variable record is declared while declaring union itself as shown in the
below program.
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
}record;
int main()
{
strcpy(record.name, "Raju");
strcpy(record.subject, "Maths");
record.percentage = 86.50;
printf(" Name
: %s \n", record.name);
printf(" Subject
: %s \n", record.subject);
printf(" Percentage : %f \n", record.percentage);
return 0;
}

Output:
Name :
Subject :
Percentage : 86.500000
Note:
We can access only one member of union at a time. We cant access all member values at the same
time in union. But, structure can access all member values at the same time. This is because, Union
allocates one common storage space for all its members. Where as Structure allocates storage space for
all its members separately.
Difference between structure and union in C:
S.no
1

C Structure
Structure allocates storage space for all its members
separately.

Structure occupies higher memory space.

Union allocates one common storage space for all


Union finds that which of its member needs high

Union occupies lower memory space over structu

We can access all members of structure at a time.


Structure example:
struct student
{
4 int mark;
char name[6];
double average;
};
For above structure, memory allocation will be like below.
int mark 2B
5 char name[6] 6B
double average 8B
Total memory allocation = 2+6+8 = 16 Bytes

We can access only one member of union at a tim


Union example:
union student
{
int mark;
char name[6];
double average;
};
For above union, only 8 bytes of memory will be
data types.
Total memory allocation = 8 Bytes

C Preprocessor directives:
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with #
symbol.
Below is the list of preprocessor directives that C language offers.
S.no
Preprocessor
1 Macro
2 Header file inclusion
Conditional
3
compilation

Syntax
#define
#include <file_name>
#ifdef, #endif, #if, #else,
#ifndef

This macro defines constant value and can be any o


The source code of the file file_name is included

Set of commands are included or excluded in sourc

#undef is used to undefine a defined macro variable


program
A program in C language involves into different processes. Below diagram will help you to understand
all the processes that a C program comes across.
4

Other directives

#undef, #pragma

Example program for #define, #include preprocessors in C:


#define - This macro defines constant value and can be any of the basic data types.
#include <file_name> - The source code of the file file_name is included in the main C
program where #include <file_name> is mentioned.
#include <stdio.h>
#define
#define
#define
#define
#define

height 100
number 3.14
letter 'A'
letter_sequence "ABC"
backslash_char '\?'

void main()
{
printf("value
printf("value
printf("value
printf("value
printf("value
}

of
of
of
of
of

height
: %d \n", height );
number : %f \n", number );
letter : %c \n", letter );
letter_sequence : %s \n", letter_sequence);
backslash_char : %c \n", backslash_char);

Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
Example program for conditional compilation directives:
a) Example program for #ifdef, #else and #endif in C:
#ifdef directive checks whether particular macro is defined or not. If it is defined, If clause
statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}

Output:
RAJU is defined. So, this line will be added in this C file
b) Example program for #ifndef and #endif in C:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, If clause
statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program);
#endif
return 0;

Output:
SELVA is not defined. So, now we are going to define here
c) Example program for #if, #else and #endif in C:
If clause statement is included in source file if given condition is true.
Otherwise, else clause statement is included in source file for compilation and execution.
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}

Output:
This line will be added in this C file since a = 100
Example program for undef in C:
This directive undefines existing macro in the program.
#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height
: %d\n",height);
#undef height
// undefining variable
#define height 600
// redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}

Output:
First defined value for height : 100
value of height after undef & redefine : 600
Example program for pragma in C:
Pragma is used to call a function before and after main function in a C program.
#include <stdio.h>

void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}

Output:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main
function
More on pragma directive in C:
S.no Pragma command
#Pragma startup
1
<function_name_1>
2

#Pragma exit <function_name_2>

3
4

#pragma warn rvl


#pragma warn par

#pragma warn rch

description
This directive executes function named function_name_1 before

This directive executes function named function_name_2 just be


program.
If function doesnt return a value, then warnings are suppressed by this d
If function doesnt use passed function parameter , then warnings are su
If a non reachable code is written inside a program, such warning
directive.