C Programming Complete Notes
C Programming Complete Notes
BHAGYASHREE ANGADI
C - NOTES
C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis
M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used
computer language.
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around the early 1970s.
The language was formalized in 1988 by the American National Standard Institute (ANSI).
The UNIX OS was totally written in C.
Today C is the most widely used and popular System Programming Language.
Most of the state-of-the-art software have been implemented using C.
Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why use C?
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
C - Program Structure
#include <stdio.h>
int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
#include <stdio.h> is a preprocessor command, which tells a C compiler to include standard input output c
library file before going to actual compilation.
The next line int main() is the main function where the program execution begins.
1
The next line /*...*/ will be ignored by the compiler. such lines are called comments in the program.
The next line printf(...) is another function available in C which causes the message "Hello, World!" to be
displayed on the screen.
The next line return 0; terminates the main() function and returns the value 0.
Tokens in C
C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or
a symbol.
Semicolons
In a C program, the semicolon is a statement terminator.
printf("Hello, World! \n");
return 0;
Identifiers
A C identifier is a name used to identify a variable, function, or any other user-defined item.
An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores,
and digits (0 to 9).
C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C.
Here are some examples of acceptable identifiers −
Keywords
The following list shows the 32 reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.
C - Data Types
Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a
variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
Integer Types
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get
the size of int type on any machine −
#include <stdio.h>
#include <limits.h>
int main() {
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
When you compile and execute the above program, it produces the following result on Linux −
3
Floating-Point Types
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
C - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. The name of a variable can
be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper
and lowercase letters are distinct because C is case-sensitive
int g = 20; // valid statement
Defining Constants
There are two simple ways in C to define constants −
You can use const prefix to declare constants with a specific type as follows −
C - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators
Arithmetic Operators
Relational Operators
Logical Operators
4
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
Modulus Operator and remainder of after an integer
% B%A=0
division.
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9
Relational Operators
Operator Description Example
Checks if the values of two operands are equal or not. If yes,
== (A == B) is not true.
then the condition becomes true.
Checks if the values of two operands are equal or not. If the
!= (A != B) is true.
values are not equal, then the condition becomes true.
Checks if the value of left operand is greater than the value
> (A > B) is not true.
of right operand. If yes, then the condition becomes true.
Checks if the value of left operand is less than the value of
< (A < B) is true.
right operand. If yes, then the condition becomes true.
Checks if the value of left operand is greater than or equal to
>= the value of right operand. If yes, then the condition (A >= B) is not true.
becomes true.
Checks if the value of left operand is less than or equal to
<= the value of right operand. If yes, then the condition (A <= B) is true.
becomes true.
Logical Operators
Operator Description Example
Called Logical AND operator. If both the operands are non-
&& (A && B) is false.
zero, then the condition becomes true.
Called Logical OR Operator. If any of the two operands is
|| (A || B) is true.
non-zero, then the condition becomes true.
5
Called Logical NOT Operator. It is used to reverse the
! logical state of its operand. If a condition is true, then !(A && B) is true.
Logical NOT operator will make it false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows −
Assignment Operators
6
Operator Description Example
Simple assignment operator. Assigns values from right side C = A + B will assign the value of A
=
operands to left side operand + B to C
Add AND assignment operator. It adds the right operand to
+= C += A is equivalent to C = C + A
the left operand and assign the result to the left operand.
Subtract AND assignment operator. It subtracts the right
-= operand from the left operand and assigns the result to the C -= A is equivalent to C = C - A
left operand.
Multiply AND assignment operator. It multiplies the right
*= operand with the left operand and assigns the result to the C *= A is equivalent to C = C * A
left operand.
Divide AND assignment operator. It divides the left operand
/= with the right operand and assigns the result to the left C /= A is equivalent to C = C / A
operand.
Modulus AND assignment operator. It takes modulus using
%= C %= A is equivalent to C = C % A
two operands and assigns the result to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
Operators Precedence in C
Operator precedence and Associativity Table in C Programming
Description Operator Associativity
Function expression () Left to Right
Array Expression [] Left to Right
Structure operators -> Left to Right
Unary minus – Right to Left
7
Increment & Decrement — ++ Right to Left
One’s compliment ~ Right to Left
Pointer Operators &* Right to Left
Type cast (data type) Right to Left
size of operator sizeof Right to Left
Left and Right Shift >> <<
Arithmetic Operators
Multiplication operator, Divide by, Modulus *, /, % Left to Right
Add, Substract +, – Left to Right
Relational Operators
Less Than < Left to Right
Greater than > Left to Right
Less than equal to <= Left to Right
Greater than equal to >= Left to Right
Equal to == Left to Right
Not equal != Left to Right
Logical Operators
AND && Left to Right
OR || Left to Right
NOT ! Right to Left
Bitwise Operators
AND & Left to Right
Exclusive OR ^ Left to Right
Inclusive OR | Left to Right
Assignment Operators
= Right to Left
*= Right to Left
/= Right to Left
%= Right to Left
+= Right to Left
-= Right to Left
&= Right to Left
^= Right to Left
|= Right to Left
<<= Right to Left
>>= Right to Left
Other Operators
Comma , Right to Left
Conditional Operator ?: Right to Left
8
Operator precedence determines the grouping of terms in an expression and decides how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement
of the colon.
9
C - Decision Making
C - if statement
Syntax
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed. If
the Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after the
closing curly brace) will be executed.
Flow Diagram
Example
#include <stdio.h>
int main ()
{
int a = 10;
if( a < 20 ) {
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result −
10
a is less than 20;
value of a is : 10
C - if...else statement
Syntax
if(boolean_expression) {
#include <stdio.h>
int main ()
{
int a = 100;
if( a < 20 ) {
printf("a is less than 20\n" );
} else {
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100
11
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
} else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
C - nested if statements
means you can use one if or else if statement inside another if or else if statement(s).
Syntax
if( boolean_expression 1) {
You can nest else if...else in the similar way as you have nested if statements.
C - switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a
case, and the variable being switched on is checked for each switch case.
Syntax
switch(expression) {
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
When the variable being switched on is equal to a case, the statements following that case will execute
until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line
following the switch statement.
12
Not every case needs to contain a break. If no break appears, the flow of control will fall through to
subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch. The
default case can be used for performing a task when none of the cases is true. No break is needed in the
default case.
Example
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
printf("Good!\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
Flow Diagram
13
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
Syntax
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>
int main () {
switch(a) {
case 100:
printf("This is part of outer switch\n", a );
switch(b) {
case 200:
printf("This is part of inner switch\n", a );
}
}
return 0;
}
14
When the above code is compiled and executed, it produces the following result −
C – Loops
A loop statement allows us to execute a statement or group of statements multiple times.
while loop in C
A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
Syntax
The syntax of a while loop in C programming language is −
while(condition) {
statement(s);
}
When the condition becomes false, the program control passes to the line immediately following the loop.
Flow Diagram
Example
#include <stdio.h>
int main () {
int a = 10;
while( a < 20 ) {
printf("value of a: %d\n", a);
15
a++; } return 0;}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
Syntax
The syntax of a for loop in C programming language is −
The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of
the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as long
as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body
of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop
terminates.
Flow Diagram
16
Example
Live Demo
#include <stdio.h>
int main () {
int a;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop in C
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.
SYNTAX
do {
17
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes
once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.
This process repeats until the given condition becomes false.
Flow Diagram
Example
#include <stdio.h>
int main () {
int a = 10;
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
18
nested loops in C
C programming allows to use one loop inside another loop. The following section shows a few examples to
illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is as follows −
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
break statement in C
The break statement in C programming has the following two usages −
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost loop and start
executing the next line of code after the block.
Syntax
The syntax for a break statement in C is as follows −
20
break;
Flow Diagram
Example
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
21
continue statement in C
The continue statement in C programming works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to execute.
For the while and do...while loops, continue statement causes the program control to pass to the conditional
tests.
Syntax
The syntax for a continue statement in C is as follows −
continue;
Flow Diagram
Example
Live Demo
#include <stdio.h>
int main () {
/* do loop execution */
do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
22
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement in C
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same
function
NOTE − Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the
control flow of a program, making the program hard to understand and hard to modify.
Syntax
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below
to goto statement.
Flow Diagram
Example
Live Demo
#include <stdio.h>
23
int main () {
/* do loop execution */
LOOP:do {
if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
24
C - Functions
Every C program has at least one function, which is main() You can divide up your code into separate
functions. How you divide up your code among different functions is up to you, but logically the division is
such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.
Defining a Function
The general form of a function definition in C programming language is as follows −
A function definition in C programming consists of a function header and a function body. Here are all the parts
of a function −
Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this case,
the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
Function Body − The function body contains a collection of statements that define what the function
does.
Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body
of the function can be defined separately.
Parameter names are not important in function declaration only their type is required, so the following is also a
valid declaration −
25
Calling a Function
To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called function
performs a defined task and when its return statement is executed or when its function-ending closing brace is
reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if the
function returns a value, then you can store the returned value. For example −
Live Demo
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
return result;
}
We have kept max() along with main() and compiled the source code. While running the final executable, it
would produce the following result −
Function Arguments
26
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry into the
function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function −
By default, C programming uses call by value to pass arguments. In general, it means the code within a function
cannot alter the arguments used to call the function.
int temp;
return;
}
Now, let us call the function swap() by passing actual values as in the following example −
#include <stdio.h>
/* function declaration */
void swap(int x, int y);
int main () {
return 0;
}
27
Let us put the above code in a single C file, compile and execute it, it will produce the following result −
It shows that there are no changes in the values, though they had been changed inside the function.
By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter
the arguments used to call the function.
To pass a value by reference, argument pointers are passed to the functions just like any other value. So
accordingly you need to declare the function parameters as pointer types as in the following function swap(),
which exchanges the values of the two integer variables pointed to, by their arguments.
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let us now call the function swap() by passing values by reference as in the following example −
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main () {
return 0;
}
Let us put the above code in a single C file, compile and execute it, to produce the following result −
It shows that the change has reflected outside the function as well, unlike call by value where the changes do
not reflect outside the function.
C - Scope Rules
A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are three places where variables can be declared in C
programming language −
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by
statements that are inside that function or block of code. Local variables are not known to functions outside
their own. The following example shows how local variables are used. Here all the variables a, b, and c are local
to main() function.
Live Demo
#include <stdio.h>
int main () {
/* actual initialization */
a = 10;
b = 20;
c = a + b;
29
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold their
values throughout the lifetime of your program and they can be accessed inside any of the functions defined for
the program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your
entire program after its declaration. The following program show how global variables are used in a program.
Live Demo
#include <stdio.h>
int main () {
/* actual initialization */
a = 10;
b = 20;
g = a + b;
return 0;
}
A program can have same name for local and global variables but the value of local variable inside a function
will take preference. Here is an example −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
30
When the above code is compiled and executed, it produces the following result −
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence over global
variables. Following is an example −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
It is a good programming practice to initialize variables properly, otherwise your program may produce
unexpected results, because uninitialized variables will take some garbage value already available at their
memory location.
C - Arrays
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable
such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific
element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest
address to the last element.
Declaring Arrays
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type
can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this
statement −
double balance[10];
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
The number of values between braces { } cannot be larger than the number of elements that we declare for the
array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you
write −
32
You will create exactly the same array as you did in the previous example. Following is an example to assign a
single element of the array −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. All arrays have 0 as the index of
their first element which is also called the base index and the last index of an array will be total size of the array
minus 1. Shown below is the pictorial representation of the array we discussed above −
The above statement will take the 10th element from the array and assign the value to salary variable.
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
33
Element[9] = 109
Multi-dimensional Arrays in C
Here is the general form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array.
To declare a two-dimensional integer array of size [x][y], you would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array
can be considered as a table which will have x number of rows and y number of columns. A two-dimensional
array a, which contains three rows and four columns can be shown as follows −
Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the
array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to
the previous example −
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal
parameter in one of following three ways and all three declaration methods produce similar results because each
tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional
arrays as formal parameters.
Way-1
Formal parameters as a pointer −
35
}
Way-2
Formal parameters as a sized array −
Way-3
Formal parameters as an unsized array −
Example
Now, consider the following function, which takes an array as an argument along with another argument and
based on the passed arguments, it returns the average of the numbers passed through the array as follows −
int i;
double avg;
double sum = 0;
return avg;
}
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main () {
36
double avg;
return 0;
}
When the above code is compiled together and executed, it produces the following result −
If you want to return a single-dimension array from a function, you would have to declare a function returning a
pointer as in the following example −
int * myFunction() {
.
.
.
}
Second point to remember is that C does not advocate to return the address of a local variable to outside of the
function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an array
and call this function as follows −
Live Demo
#include <stdio.h>
return r;
}
37
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom();
return 0;
}
When the above code is compiled together and executed, it produces the following result −
r[0] = 313959809
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
r[5] = 167288147
r[6] = 1827471542
r[7] = 834791014
r[8] = 1901409888
r[9] = 1990469526
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
*(p + 5) : 167288147
*(p + 6) : 1827471542
*(p + 7) : 834791014
*(p + 8) : 1901409888
Pointer to an Array in C
It is most likely that you would not understand this section until you are through with the chapter 'Pointers'.
Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the
first element of the array. Therefore, in the declaration −
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the
following program fragment assigns p as the address of the first element of balance −
double *p;
double balance[10];
p = balance;
38
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way
of accessing the data at balance[4].
Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2)
and so on. Given below is the example to show all the concepts discussed above −
Live Demo
#include <stdio.h>
int main () {
p = balance;
return 0;
}
When the above code is compiled and executed, it produces the following result −
In the above example, p is a pointer to double, which means it can store the address of a variable of double type.
Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown
in the above example.
C - Pointers
39
C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory
allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a
perfect C programmer. As you know, every variable is a memory location and every memory location has its
address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.
Consider the following example, which prints the address of the variables defined −
Live Demo
#include <stdio.h>
int main () {
int var1;
char var2[10];
return 0;
}
When the above code is compiled and executed, it produces the following result −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer
declarations −
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a
long hexadecimal number that represents a memory address. The only difference between pointers of different
data types is the data type of the variable or constant that the pointer points to.
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
41
In most of the operating systems, programs are not permitted to access memory at address 0 because that
memory is reserved by the operating system. However, the memory address 0 has special significance; it signals
that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer
contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows −
Pointers in Detail
Pointers have many but easy concepts and they are very important to C programming. The following important
pointer concepts should be clear to any C programmer −
C - Pointer arithmetic
A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a
pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++,
--, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000.
Assuming 32-bit integers, let us perform the following arithmetic operation on the pointer −
ptr++
After the above operation, the ptr will point to the location 1004 because each time ptr is incremented, it will
point to the next integer location which is 4 bytes next to the current location. This operation will move the
pointer to the next memory location without impacting the actual value at the memory location. If ptr points to
a character whose address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001.
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be incremented,
unlike the array name which cannot be incremented because it is a constant pointer. The following program
increments the variable pointer to access each succeeding element of the array −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Decrementing a Pointer
The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of
its data type as shown below −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables
that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully
compared.
The following program modifies the previous example − one by incrementing the variable pointer so long as the
address to which it points is either less than or equal to the address of the last element of the array, which is
&var[MAX - 1] −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
C - Array of pointers
44
Before we understand the concept of arrays of pointers, let us consider the following example, which uses an
array of 3 integers −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation when we want to maintain an array, which can store pointers to an int or char or any
other data type available. Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int value.
The following example uses three integers, which are stored in an array of pointers, as follows −
Live Demo
#include <stdio.h>
int main () {
return 0;
}
45
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as follows −
Live Demo
#include <stdio.h>
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
return 0;
}
When the above code is compiled and executed, it produces the following result −
C - Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk
in front of its name. For example, the following declaration declares a pointer to a pointer of type int −
int **var;
46
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk operator be applied twice, as is shown below in the example −
Live Demo
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Following is a simple example where we pass an unsigned long pointer to a function and change the value
inside the function which reflects back in the calling function −
Live Demo
#include <stdio.h>
#include <time.h>
int main () {
47
printf("Number of seconds: %ld\n", sec );
return 0;
}
When the above code is compiled and executed, it produces the following result −
The function, which can accept a pointer, can also accept an array as shown in the following example −
Live Demo
#include <stdio.h>
/* function declaration */
double getAverage(int *arr, int size);
int main () {
int i, sum = 0;
double avg;
When the above code is compiled together and executed, it produces the following result −
int * myFunction() {
.
.
.
}
Second point to remember is that, it is not a good idea to return the address of a local variable outside the
function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an array
name which represents a pointer, i.e., address of first array element.
Live Demo
#include <stdio.h>
#include <time.h>
return r;
}
/* a pointer to an int */
int *p;
int i;
p = getRandom();
return 0;
}
When the above code is compiled together and executed, it produces the following result −
1523198053
49
1187214107
1108300978
430494959
1421301276
930971084
123250484
106932140
1604461820
149169022
*(p + [0]) : 1523198053
*(p + [1]) : 1187214107
*(p + [2]) : 1108300978
*(p + [3]) : 430494959
*(p + [4]) : 1421301276
*(p + [5]) : 930971084
*(p + [6]) : 123250484
*(p + [7]) : 106932140
*(p + [8]) : 1604461820
*(p + [9]) : 149169022
C - Strings
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null
character at the end of the array, the size of the character array containing the string is one more than the
number of characters in the word "Hello."
If you follow the rule of array initialization then you can write the above statement as follows −
Actually, you do not place the null character at the end of a string constant. The C compiler automatically
places the '\0' at the end of the string when it initializes the array. Let us try to print the above mentioned string
−
Live Demo
50
#include <stdio.h>
int main () {
When the above code is compiled and executed, it produces the following result −
Live Demo
#include <stdio.h>
#include <string.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
C - Structures
Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is
another user defined data type available in C that allows to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might
want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data type, with
more than one member. The format of the struct statement is as follows −
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float
f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you
can specify one or more structure variables but it is optional. Here is the way you would declare the Book
structure −
struct Books {
char title[50];
52
char author[50];
char subject[100];
int book_id;
} book;
Live Demo
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result −
53
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Live Demo
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any other variable −
Now, you can store the address of a structure variable in the above defined pointer variable. To find the address
of a structure variable, place the '&'; operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the → operator as follows −
struct_pointer->title;
Live Demo
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
55
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Bit Fields
Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a
premium. Typical examples include −
Packing several objects into a machine word. e.g. 1 bit flags can be compacted.
Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.
C allows us to do this in a structure definition by putting :bit length after the variable. For example −
struct packed_struct {
unsigned int f1:1;
unsigned int f2:1;
unsigned int f3:1;
unsigned int f4:1;
unsigned int type:4;
unsigned int my_int:9;
} pack;
Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int.
56
C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the
field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers
may allow memory overlap for the fields while others would store the next field in the next word.
C - Unions
A union is a special data type available in C that allows to store different data types in the same memory
location. You can define a union with many members, but only one member can contain a value at any given
time. Unions provide an efficient way of using the same memory location for multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a structure. The
union statement defines a new data type with more than one member for your program. The format of the union
statement is as follows −
The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or
any other valid variable definition. At the end of the union's definition, before the final semicolon, you can
specify one or more union variables but it is optional. Here is the way you would define a union type named
Data having three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. It means a
single variable, i.e., same memory location, can be used to store multiple types of data. You can use any built-in
or user defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest member of the union. For example, in
the above example, Data type will occupy 20 bytes of memory space because this is the maximum space which
can be occupied by a character string. The following example displays the total memory size occupied by the
above union −
Live Demo
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
57
char str[20];
};
int main( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result −
Live Demo
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
58
Here, we can see that the values of i and f members of union got corrupted because the final value assigned to
the variable has occupied the memory location and this is the reason that the value of str member is getting
printed very well.
Now let's look into the same example once again where we will use one variable at a time which is the main
purpose of having unions −
Live Demo
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.
C - Bit Fields
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as
follows −
struct {
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual, we are going to store either 0 or 1 in each of the
variables. The C programming language offers a better way to utilize the memory space in such situations.
59
If you are using such variables inside a structure then you can define the width of a variable which tells the C
compiler that you are going to use only those number of bytes. For example, the above structure can be re-
written as follows −
struct {
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
The above structure requires 4 bytes of memory space for status variable, but only 2 bits will be used to store
the values.
If you will use up to 32 variables each one with a width of 1 bit, then also the status structure will use 4 bytes.
However as soon as you have 33 variables, it will allocate the next slot of the memory and it will start using 8
bytes. Let us check the following example to understand the concept −
Live Demo
#include <stdio.h>
#include <string.h>
int main( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result −
struct {
type [member_name] : width ;
};
The variables defined with a predefined width are called bit fields. A bit field can hold more than a single bit;
for example, if you need a variable to store a value from 0 to 7, then you can define a bit field with a width of 3
bits as follows −
struct {
unsigned int age : 3;
} Age;
The above structure definition instructs the C compiler that the age variable is going to use only 3 bits to store
the value. If you try to use more than 3 bits, then it will not allow you to do so. Let us try the following example
−
Live Demo
#include <stdio.h>
#include <string.h>
struct {
unsigned int age : 3;
} Age;
int main( ) {
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
When the above code is compiled it will compile with a warning and when executed, it produces the following
result −
Sizeof( Age ) : 4
61
Age.age : 4
Age.age : 7
Age.age : 0
C - typedef
The C programming language provides a keyword called typedef, which you can use to give a type a new
name. Following is an example to define a term BYTE for one-byte numbers −
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for
example..
By convention, uppercase letters are used for these definitions to remind the user that the type name is really a
symbolic abbreviation, but you can use lowercase, as follows −
You can use typedef to give a name to your user defined data types as well. For example, you can use typedef
with structure to define a new data type and then use that data type to define structure variables directly as
follows −
Live Demo
#include <stdio.h>
#include <string.h>
int main( ) {
Book book;
return 0;
}
62
When the above code is compiled and executed, it produces the following result −
typedef vs #define
#define is a C-directive which is also used to define the aliases for various data types similar to typedef but
with the following differences −
typedef is limited to giving symbolic names to types only where as #define can be used to define alias
for values as well, q., you can define 1 as ONE etc.
typedef interpretation is performed by the compiler whereas #define statements are processed by the
pre-processor.
Live Demo
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main( ) {
printf( "Value of TRUE : %d\n", TRUE);
printf( "Value of FALSE : %d\n", FALSE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of TRUE : 1
Value of FALSE : 0
When we say Output, it means to display some data on screen, printer, or in any file. C programming provides
a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.
63
C programming treats all the devices as files. So devices such as the display are addressed in the same way as
files and the following three files are automatically opened when a program executes to provide access to the
keyboard and screen.
The file pointers are the means to access the file for reading and writing purpose. This section explains how to
read values from the screen and how to print the result on the screen.
The int putchar(int c) function puts the passed character on the screen and returns the same character. This
function puts only single character at a time. You can use this method in the loop in case you want to display
more than one character on the screen. Check the following example −
#include <stdio.h>
int main( ) {
int c;
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and
press enter, then the program proceeds and reads only a single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
64
#include <stdio.h>
int main( ) {
char str[100];
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and
press enter, then the program proceeds and reads the complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The int printf(const char *format, ...) function writes the output to the standard output stream stdout and
produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings,
integer, character or float respectively. There are many other formatting options available which can be used
based on requirements. Let us now proceed with a simple example to understand the concepts better −
#include <stdio.h>
int main( ) {
char str[100];
int i;
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and
press enter, then program proceeds and reads the input and displays it as follows −
$./a.out
Enter a value : seven 7
You entered: seven 7
65
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means
you have to provide valid inputs like "string integer". If you provide "string string" or "integer integer", then it
will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters
a space, so "this is test" are three strings for scanf().
C - File I/O
The last chapter explained the standard input and output devices handled by C programming language. This
chapter cover how C programmers can create, open, close text or binary files for their data storage.
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language
provides access on high level functions as well as low level (OS level) calls to handle file on your storage
devices. This chapter will take you through the important calls for file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an
object of the type FILE, which contains all the information necessary to control the stream. The prototype of
this function call is as follows −
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the
following values −
66
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will
start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use following access modes instead of the above
mentioned ones −
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function
actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for
the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in
the form of a fixed length string.
Writing a File
Following is the simplest function to write individual characters to a stream −
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It
returns the written character written on success otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream −
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on
success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char
*format, ...) function as well to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory
on your machine.
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
67
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two
lines using two different functions. Let us read this file in the next section.
Reading a File
Given below is the simplest function to read a single character from a file −
The fgetc() function reads a character from the input file referenced by fp. The return value is the character
read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string
into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the
maximum number of characters, then it returns only the characters read up to that point including the new line
character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file,
but it stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
When the above code is compiled and executed, it reads the file created in the previous section and produces the
following result −
1 : This
2: is testing for fprintf...
Let's see a little more in detail about what happened here. First, fscanf() read just This because after that, it
encountered a space, second call is for fgets() which reads the remaining line till it encountered end of line.
Finally, the last call fgets() reads the second line completely.
68
Binary I/O Functions
There are two functions, that can be used for binary input and output −
Both of these functions should be used to read or write blocks of memories - usually arrays or structures.
C - Preprocessors
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple
terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing
before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for
readability, a preprocessor directive should begin in the first column. The following section lists down all the
important preprocessor directives −
69
#else and #if in one statement.
#endif
9
Ends preprocessor conditional.
#error
10
Prints error message on stderr.
#pragma
11
Issues special commands to the compiler, using a standardized method.
Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for
constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file.
The next line tells CPP to get myheader.h from the local directory and add the content to the current source
file.
#undef FILE_SIZE
#define FILE_SIZE 42
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -
DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn
debugging on and off on the fly during compilation.
Predefined Macros
70
ANSI C defines a number of macros. Although each one is available for use in programming, the predefined
macros should not be directly modified.
Live Demo
#include <stdio.h>
int main() {
When the above code in a file test.c is compiled and executed, it produces the following result −
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
Preprocessor Operators
The C preprocessor offers the following operators to help create macros −
71
A macro is normally confined to a single line. The macro continuation operator (\) is used to continue a macro
that is too long for a single line. For example −
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter
into a string constant. This operator may be used only in a macro having a specified argument or parameter list.
For example −
Live Demo
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void) {
message_for(Carole, Debra);
return 0;
}
When the above code is compiled and executed, it produces the following result −
The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate
tokens in the macro definition to be joined into a single token. For example −
Live Demo
#include <stdio.h>
int main(void) {
int token34 = 40;
tokenpaster(34);
return 0;
}
When the above code is compiled and executed, it produces the following result −
token34 = 40
It happened so because this example results in the following actual output from the preprocessor −
72
This example shows the concatenation of token##n into token34 and here we have used both stringize and
token-pasting.
The preprocessor defined operator is used in constant expressions to determine if an identifier is defined using
#define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value
is false (zero). The defined operator is specified as follows −
Live Demo
#include <stdio.h>
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For
example, we might have some code to square a number as follows −
int square(int x) {
return x * x;
}
Macros with arguments must be defined using the #define directive before they can be used. The argument list
is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the
macro name and open parenthesis. For example −
Live Demo
#include <stdio.h>
int main(void) {
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
73
When the above code is compiled and executed, it produces the following result −
C - Header Files
A header file is a file with extension .h which contains C function declarations and macro definitions to be
shared between several source files. There are two types of header files: the files that the programmer writes
and the files that comes with your compiler.
You request to use a header file in your program by including it with the C preprocessing directive #include,
like you have seen inclusion of stdio.h header file, which comes along with your compiler.
Including a header file is equal to copying the content of the header file but we do not do it because it will be
error-prone and it is not a good idea to copy the content of a header file in the source files, especially if we have
multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide global variables,
and function prototypes in the header files and include that header file wherever it is required.
Include Syntax
Both the user and the system header files are included using the preprocessing directive #include. It has the
following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of system
directories. You can prepend directories to this list with the -I option while compiling your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the directory
containing the current file. You can prepend directories to this list with the -I option while compiling your
source code.
Include Operation
The #include directive works by directing the C preprocessor to scan the specified file as input before
continuing with the rest of the current source file. The output from the preprocessor contains the output already
generated, followed by the output resulting from the included file, followed by the output that comes from the
text after the #include directive. For example, if you have a header file header.h as follows −
74
and a main program called program.c that uses the header file, like this −
int x;
#include "header.h"
the compiler will see the same token stream as it would if program.c read.
int x;
char *test (void);
Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice and it will result in an
error. The standard way to prevent this is to enclose the entire real contents of the file in a conditional, like this
−
#ifndef HEADER_FILE
#define HEADER_FILE
#endif
This construct is commonly known as a wrapper #ifndef. When the header is included again, the conditional
will be false, because HEADER_FILE is defined. The preprocessor will skip over the entire contents of the file,
and the compiler will not see it twice.
Computed Includes
Sometimes it is necessary to select one of the several different header files to be included into your program.
For instance, they might specify configuration parameters to be used on different sorts of operating systems.
You could do this with a series of conditionals as follows −
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif
But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for the header
name. This is called a computed include. Instead of writing a header name as the direct argument of #include,
you simply put a macro name there −
75
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H
SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include had been
written that way originally. SYSTEM_H could be defined by your Makefile with a -D option.
C - Type Casting
Type casting is a way to convert a variable from one data type to another data type. For example, if you want to
store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from
one type to another explicitly using the cast operator as follows −
(type_name) expression
Consider the following example where the cast operator causes the division of one integer variable by another
to be performed as a floating-point operation −
Live Demo
#include <stdio.h>
main() {
When the above code is compiled and executed, it produces the following result −
It should be noted here that the cast operator has precedence over division, so the value of sum is first converted
to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be specified
explicitly through the use of the cast operator. It is considered good programming practice to use the cast
operator whenever type conversions are necessary.
Integer Promotion
Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are
converted either to int or unsigned int. Consider an example of adding a character with an integer −
Live Demo
#include <stdio.h>
main() {
76
int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
sum = i + c;
printf("Value of sum : %d\n", sum );
}
When the above code is compiled and executed, it produces the following result −
Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of 'c' to
ASCII before performing the actual addition operation.
The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators
&& and ||. Let us take the following example to understand the concept −
Live Demo
#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
77
}
When the above code is compiled and executed, it produces the following result −
Here, it is simple to understand that first c gets converted to integer, but as the final value is double, usual
arithmetic conversion applies and the compiler converts i and c into 'float' and adds them yielding a 'float' result.
C - Error Handling
Advertisements
Previous Page
Next Page
As such, C programming does not provide direct support for error handling but being a system programming
language, it provides you access at lower level in the form of return values. Most of the C or even Unix function
calls return -1 or NULL in case of any error and set an error code errno. It is set as a global variable and
indicates an error occurred during any function call. You can find various error codes defined in <error.h>
header file.
So a C programmer can check the returned values and can take appropriate action depending on the return
value. It is a good practice, to set errno to 0 at the time of initializing a program. A value of 0 indicates that
there is no error in the program.
The perror() function displays the string you pass to it, followed by a colon, a space, and then the
textual representation of the current errno value.
The strerror() function, which returns a pointer to the textual representation of the current errno value.
Let's try to simulate an error condition and try to open a file which does not exist. Here I'm using both the
functions to show the usage, but you can use one or more ways of printing your errors. Second important point
to note is that you should use stderr file stream to output all the errors.
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main () {
78
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
} else {
fclose (pf);
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory
The code below fixes this by checking if the divisor is zero before dividing −
Live Demo
#include <stdio.h>
#include <stdlib.h>
main() {
exit(0);
}
When the above code is compiled and executed, it produces the following result −
79
Program Exit Status
It is a common practice to exit with a value of EXIT_SUCCESS in case of program coming out after a
successful operation. Here, EXIT_SUCCESS is a macro and it is defined as 0.
If you have an error condition in your program and you are coming out then you should exit with a status
EXIT_FAILURE which is defined as -1. So let's write above program as follows −
Live Demo
#include <stdio.h>
#include <stdlib.h>
main() {
if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
When the above code is compiled and executed, it produces the following result −
Value of quotient : 4
C - Recursion
Advertisements
Previous Page
Next Page
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
80
The C programming language supports recursion, i.e., a function to call itself. But while using recursion,
programmers need to be careful to define an exit condition from the function, otherwise it will go into an
infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.
Number Factorial
The following example calculates the factorial of a given number using a recursive function −
Live Demo
#include <stdio.h>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
Live Demo
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
81
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
0
1
1
2
3
5
8
13
21
34
C - Variable Arguments
Advertisements
Previous Page
Next Page
Sometimes, you may come across a situation, when you want to have a function, which can take variable
number of arguments, i.e., parameters, instead of predefined number of parameters. The C programming
language provides a solution for this situation and you are allowed to define a function which can accept
variable number of parameters based on your requirement. The following example shows the definition of such
a function.
int main() {
func(1, 2, 3);
func(1, 2, 3, 4);
}
It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just
before the ellipses is always an int which will represent the total number variable arguments passed. To use
such functionality, you need to make use of stdarg.h header file which provides the functions and macros to
implement the functionality of variable arguments and follow the given steps −
82
Define a function with its last parameter as ellipses and the one just before the ellipses is always an int
which will represent the number of arguments.
Create a va_list type variable in the function definition. This type is defined in stdarg.h header file.
Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro
va_start is defined in stdarg.h header file.
Use va_arg macro and va_list variable to access each item in argument list.
Use a macro va_end to clean up the memory assigned to va_list variable.
Now let us follow the above steps and write down a simple function which can take the variable number of
parameters and return their average −
Live Demo
#include <stdio.h>
#include <stdarg.h>
va_list valist;
double sum = 0.0;
int i;
return sum/num;
}
int main() {
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}
When the above code is compiled and executed, it produces the following result. It should be noted that the
function average() has been called twice and each time the first argument represents the total number of
variable arguments being passed. Only ellipses will be used to pass variable number of arguments.
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000
C - Memory Management
Advertisements
Previous Page
83
Next Page
This chapter explains dynamic memory management in C. The C programming language provides several
functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.
char name[100];
But now let us consider a situation where you have no idea about the length of the text you need to store, for
example, you want to store a detailed description about a topic. Here we need to define a pointer to character
without defining how much memory is required and later, based on requirement, we can allocate memory as
shown in the below example −
Live Demo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
When the above code is compiled and executed, it produces the following result.
Same program can be written using calloc(); only thing is you need to replace malloc with calloc as follows −
calloc(200, sizeof(char));
So you have complete control and you can pass any size value while allocating memory, unlike arrays where
once the size defined, you cannot change it.
Alternatively, you can increase or decrease the size of an allocated memory block by calling the function
realloc(). Let us check the above program once again and make use of realloc() and free() functions −
Live Demo
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
85
fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcat( description, "She is in class 10th");
}
When the above code is compiled and executed, it produces the following result.
You can try the above example without re-allocating extra memory, and strcat() function will give an error due
to lack of available memory in description.
Previous Page
Next Page
It is possible to pass some values from the command line to your C programs when they are executed. These
values are called command line arguments and many times they are important for your program especially
when you want to control your program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the number of
arguments passed, and argv[] is a pointer array which points to each argument passed to the program.
Following is a simple example which checks if there is any argument supplied from the command line and take
action accordingly −
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
86
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.
When the above code is compiled and executed without passing any argument, it produces the following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first
command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be
one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then you can
pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example
once again where we will print program name and we also pass a command line argument by putting inside
double quotes −
#include <stdio.h>
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside double
quotes, it produces the following result.
87
C Programming Interview Questions
It’s a pointer variable which can hold the address of another pointer variable. It de-refers twice to point to the
data held by the designated pointer variable.
Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.
By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’
and ‘j’ are automatic variables.
void f() {
int i;
auto int j;
}
What are the valid places for the keyword break to appear.
Break can appear only with in the looping control and switch statement. The purpose of the break is to bring the
control out from the said blocks.
When control reaches for expression-1 is executed first. Then following expression-2, and if expression-2
evaluates to non-zero ‘set of statements’ and expression-3 is executed, follows expression-2.
What is difference between including the header file with-in angular braces < > and double quotes “ “
88
If a header file is included with in < > then the compiler searches for the particular header file only with in the
built in include path. If a header file is included with in “ “, then the compiler searches for the particular header
file first in the current working directory, if not found then in the built in include path.
Get the two’s compliment of the same positive integer. Eg: 1011 (-5)
A static local variables retains its value between the function call and the default value is 0. The following
function will print 1 2 3 if called thrice.
void f() {
static int i;
++i;
printf(“%d “,i);
}
If a global variable is static then its visibility is limited to the same source code.
Eg:
main() {
extern int i;
Printf(“%d”,i);
}
int i = 20;
Explain the purpose of the function sprintf().
The starting address of the array is called as the base address of the array.
89
If a variable is used most frequently then it should be declared using register storage specifier, then possibly the
compiler gives CPU register for its storage to speed up the look up of the variable.
S++ or S = S+1, which can be recommended to increment the value by 1 and why?
A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is
called as dangling pointer.
It is used to alias the existing type. Also used to simplify the complex declaration of the type.
The expression appearing on right side of the assignment operator is called as rvalue. Rvalue is assigned to
lvalue, which appears on left side of the assignment operator. The lvalue should designate to a variable not a
constant.
The parameters sent to the function at calling end are called as actual parameters while at the receiving of the
function definition called as formal parameters.
Yes, it can be but cannot be executed, as the execution requires main() function definition.
When we do not know what type of the memory address the pointer variable is going to hold, then we declare a
void pointer for such.
Every local variable by default being an auto variable is stored in stack memory.
Declaration associates type to the variable whereas definition gives the value to the variable.
90
What is a self-referential structure?
A structure containing the same structure pointer variable as its element is called as self-referential structure.
No, the header file only declares function. The definition is in library which is linked by the linker.
Dividing the program in to sub programs (modules/function) to achieve the given task is modular approach.
More generic functions definition gives the ability to re-use the functions, such as built-in library functions.
What is a token?
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal,
or a symbol.
What is a preprocessor?
Preprocessor is a directive to the compiler to perform certain things before the actual compilation process
begins.
How can you print a \ (backslash) using any of the printf() family of functions.
Yes, if it is not appearing as the last case and if we do not want the control to flow to the following case after
default if any.
If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is
used.
We can create integer structure members of differing size apart from non-standard size using bit fields. Such
structure size is automatically adjusted with the multiple of integer size of the machine.
91
The arguments which we pass to the main() function while executing the program are called as command line
arguments. The parameters are always strings held in the second argument (below in args) of the function which
is array of character pointers. First argument represents the count of arguments (below in count) and updated
automatically by operating system.
Call by value − We send only values to the function as parameters. We choose this if we do not want
the actual parameters to be modified with formal parameters but just used.
Call by reference − We send address of the actual parameters instead of values. We choose this if we
do want the actual parameters to be modified with formal parameters.
Opens a file both for reading and writing. If a file is not existing it creates one, else if the file is existing it will
be over written.
It cannot be used on variable which are declared using register storage class.
Error, It is invalid that either of the operands for the modulus operator (%) is a real number.
How many operators are there under the category of ternary operators?
goto
What is a pointer to a function? Give the general syntax for the same.
A pointer holding the reference of the function is called pointer to a function. In general it is declared as
follows.
92
T (*fun_ptr) (T1,T2…); Where T is any date type.
Once fun_ptr refers a function the same can be invoked using the pointer as follows.
fun_ptr();
[Or]
(*fun_ptr)();
Explain the use of comma operator (,).
A function’s definition prefixed with static keyword is called as a static function. You would make a function
static if it should be called only within the same source code.
Which compiler switch to be used for compiling the programs using math library with gcc compiler?
Which operator is used to continue the definition of macro in the next line?
Welcome to C"
Which operator is used to receive the variable number of arguments for a function?
Ellipses (…) is used for the same. A general function definition looks as follows
strcat(s1,s2);
Which built-in library function can be used to re-size the allocated dynamic memory?
93
realloc().
Define an array.
Enumerations are list of integer constants with name. Enumerators are defined with the keyword enum.
Which built-in function can be used to move the file pointer internally?
fseek()
What is a variable?
Dennis M Ritchie.
Which operator can be used to determine the size of a data type or variable?
sizeof
94
If both the corresponding bits are same it gives 0 else 1.
while(0 == 0) {
}
Can variables belonging to different scope have same name? If so show an example.
Variables belonging to different scope can have same name as in the following code snippet.
int var;
void f() {
int var;
}
main() {
int var;
}
What is the default value of local and global variables?
Local variables get garbage value and global variables get a value 0 by default.
Which operator can be used to access union elements if union variable is a pointer variable?
stdin in a pointer variable which is by default opened for standard input device.
95
Name a function which can be used to close the file stream.
fclose().
Define a structure.
Name the predefined macro which be used to determine whether your compiler is ANSI standard or not?
__STDC__
What is typecasting?
What is recursion?
free().
What is the first string in the argument vector w.r.t command line arguments?
Program name.
How can we determine whether a file is successfully opened or not using fopen() function?
96
Functions must and should be declared. Comment on this.
Can a function return multiple values to the caller using return reserved word?
A pointer which is not allowed to be altered to hold another address after it is holding one.
Void
Which built-in library function can be used to match a patter from the string?
Strstr()
In first place they are non-standard keywords. A near pointer can access only 2^15 memory space and far
pointer can access 2^32 memory space. Both the keywords are implementation specific and are non-standard.
No, we cannot.
Which control loop is recommended if you have to execute set of statements for fixed number of times?
for – Loop.
What is a constant?
A value which cannot be modified is called so. Such variables are qualified with the keyword const.
97
Can we use just the tag name of structures to declare the variables for the same?
No, we need to use both the keyword ‘struct’ and the tag name.
Apart from Dennis Ritchie who the other person who contributed in design of C language.
Brain Kernighan
We use # include to include a file. The difference between two ways of file inclusion lies in the order
in which preprocessor searches for the file specified. When the preprocessor encounters
#include<file> statement, it looks for the file specified in the angled brackets in the default location
(Path defined in INCLUDE environment variable of the system).
When # include followed by file name in double quotation marks is encountered by the preprocessor,
it looks for the file in the current directory. If the file is not found in the current directory, it will look for
the file in the default location.
Yes. Irrespective of the file type, Preprocessor will do its job and will include any file like test.z.
A void pointer is a special pointer type which can point to any data type without letting the compiler
know. It helps to pass a pointer to some function of any type which can be decided at run time. In the
following example input parameter a and b can be both integer and string.
98
*c = ((int) *a) + ((int)*b);
else /*string*/
sprintf((char*)c,”%s%s”,(char*)a,(char*b));
The value of NULL is 0 or (void*)0. Whenever NULL has to be compared with some variable or
assigned to a variable, depending upon the type of that variable, the value of NULL will be decided.
No. The size of an array must be stated at the time of compilation. Alternate way is to use dynamic
allocation by calloc or malloc.
Calloc Malloc
The heap is where malloc(), calloc(), and realloc() get memory. The allocation of memory from the
heap is much slower than the stack. But, the heap is much more flexible about memory allocation
than the stack. Memory can be allocated and deallocated in any time and order. This heap memory
isn't deallocated by itself, method free() has to be called in order to do so.
float num1 = 6 / 4;
99
printf("6/4 == %f or %f\n", num1, num2);
Output will be : 6/4 == 1.000000 or 1. 500000. This is a case of operator promotion. The variable
num1 is set to “6/4”. Because, both 3 and 4 are integers. So integer division is performed on them
and the result is the integer 0. The variable num2 is set to “6/4.0”. Because 4.0 is a float, the number
6 is converted to a float as well, and the result will be floating value 1.5.
It is really dangerous to free the same memory twice. If the memory has not been reallocated in
between, it will generate a “double free” error, since the memory location has already been freed.
10) How does free() method know about how much memory to release?
There's no concrete way. Most systems, keeps a track of each memory block as linked lists. When
memory is allocated, all the blocks that are given to that particular call are put into a linked list and the
size, block number and serial number are written in the head node. There is no assurance, though.
But in some way or other, the system keeps track of each block to know the size of each allocated
portion of the heap.
11) How to restrict a header file from including more than once?
In C, to avoid double inclusion, we use a include guard also known as macro guard. It is #ifndef -
#endif pair. "ifndef" is an indication of “if not defined”.
#ifndef FAMILY_H
#define FAMILY_H
struct Example
int member;
};
#endif /* FAMILY _H */
100
The best way is to use "%p" in printf() or fprintf. The “%p” will tell compiler to use the best type to
use, while printing the address according to the environment, since the size of a pointer changes from
system to system.
#include <stdio.h>
int main()
int i;
scanf("%d",&i);
return 0;
The answer is : 1 2 3 4 3 4 5
Explanation: The enum assigns the value with single increment. If a value is explicitly assigned to an
element, it will just set that value to that element and start to increment from that assigned value for
the following elements.
14) Explain recursive functions? Also explain the advantages and disadvantages of Recursive
algorithms?
A recursive function is a function which calls itself. The advantages of recursive functions are:
A substitute for very complex iteration. For example, a recursive function is best to reduce the code
size for Tower of Hanoi application.
Unnecessary calling of functions can be avoided.
101
The disadvantages of Recursive functions:
The exit point must be explicitly coded ,otherwise stack overflow may happen
A recursive function is often confusing. It is difficult to trace the logic of the function. Hence, it is
difficult to debug a recursive function.
The #pragma preprocessor allows compiler to include or exclude compiler specific features. For
example if there is a feature xxx_yyy then,
#pragma xxx_yyy(on)
Forces compiler to include the feature. Conversely, you can turn off it by the following lines:
#pragma xxx_yyy(off)
#endif
An lvalue is an expression to which a value can be assigned. The lvalue expression is the one which
is located on the left side a statement, whereas an rvalue is located on the right side of a statement.
Each assignment must have a valid lvalue and rvalue. The lvalue expression must refer to a storage
where something can be stored. It can't be a constant.
102
You can't assign an array to other. Arrays are not lvalue, because they don't refer to one variable,
rather a set of variables. So they can't be placed on the left hand side of an assignment statement.
For example the following statement will generate compilation error.
x = y;
20) what is the order of operator precedence, left to right or right to left ?
None of them is standard. C does not always start evaluating left to right or right to left. Normally,
function calls are done first, followed by complex expressions and then simple expressions. That is
why it is best to use parenthesis in all expressions, without depending on precedence.
The ++ operator is called the incremental operator. When the operator is placed before, the variable
is incremented by 1 before it is used in the statement. When the operator is placed after the variable,
then the expression is evaluated first and then the variable is incremented by 1.
It depends upon the type of the pointer. It gets incremented by the size of the data type, the pointer is
pointing to. For example
int num1=5;
int num2=5;
printf("num1=%d num2=%d",num1,num2);
No. The sizeof() operator can't tell the size of an array, because it is actually a pointer to the data type
of the array.
No. An array tag can't be used as a storage, because it is not an Lvalue. It can be thought as a
pointer to the datatype of the array which is constant and which can't be changed or assigned
dynamically.
A stream is a series of data bytes which serves the input and output needs of a program. Input and
output from devices are generally connected to these streams which then appears as logical file
descriptors to your program. In C, there are five such standard streams which need not be opened or
closed explicitly.
Streams can be classified into two types: text streams and binary streams. The text streams are
interpreted as per the ASCII values starting from 0 to 255. Binary streams are raw bytes which C can't
interpret, but application has to interpret it itself. Text modes are used to handle, generally text file
where as binary modes can be used for all files. But they won't give you the content of a file, rather
they will give you the file properties and content in raw binary format.
Stream files are generally better to use, since they provide sufficient amount of buffer for read and
write. That is why it is more efficient.
104
But in a multiuser environment, files can be shared among users. These shared files are secured with
lock, where only one user will be able to write at a time. In this scenario, buffering will not be efficient,
since the file content will change continuously and it will be slower.
So, normally it is good to use stream functions, but for shared files system calls are better.
29) What is the difference between a string copy (strcpy) and a memory copy (memcpy)?
Generally speaking, they both copy a number of bytes from a source pointer to a destination pointer.
But the basic difference is that the strcpy() is specifically designed to copy strings, hence it stops
copying after getting the first '\0'(NULL) character. But memcpy() is designed to work with all data
types. So you need to specify the length of the data to be copied, starting from the source pointer.
printf("%-20.20s", data[d]);
The "%-20.20s" argument tells the printf() function that you are printing a string and you want to
force it to be 20 characters long. By default, the string is right justified, but by including the minus sign
(-) before the first 20, you tell the printf() function to left-justify your string. This action forces the
printf() function to pad the string with spaces to make it 20 characters long.
You can write your own functions too, because these functions are not that safe, as they don't check
if the value given is NULL or not.
The access modifier keyword “const” tells compiler that the value of this variable is not going to be
changed after it is initialized. The compiler will enforce it throughout the lifetime of the variable.
105
33) char *p="SAMPLETEXT" , *q ="SAMPLETEXT"; Are these two pointers equal ? If yes , then
explain ?
In C, strings(not array of characters) are immutable. This means that a string once created cannot be
modified. Only flushing the buffer can remove it. Next point is, when a string is created it is stored in
buffer. Next time, when a new string is created, it will check whether that string is present in buffer or
not. If present, that address is assigned. Otherwise, new address stores the new string and this new
address is assigned.
The first one is to convert some value of datatype A to a datatype B. Such as, if you type cast a float
variable of value 1.25 to int, then it will be 1.
The second use is to cast any pointer type to and from void *, in order to use it in generic functions
such as memory copy functions, where the execution is independent of the type of the pointer.
35) What is the difference between declaring a variable and defining a variable?
Declaration is done to tell compiler the data type of the variable, and it inherently meant that
somewhere in this scope, this variable is defined or will be defined. And defining a variable means to
allocate space for that variable and register it in the stack memory. For example:
You can't declare a static variable without definition (this is because they are mutually exclusive
storage classes). A static variable can be defined in a header file, but then every source file with in
that scope will have their own copy of this variable, which is intended.
37) What is the benefit of using const for declaring constants over #define?
The basic difference between them is that, a const variable is a real variable which has a datatype
and it exists at run time, and it can't be altered. But a macro is not a real variable, but it carries a
constant value which replaces all the occurrences of that macro at the time of pre-processing.
Static function is a special type of function whose scope is limited to the source file where the function
is defined and can not be used other than that file. This feature helps you to hide some functions and
to provide some standard interface or wrapper over that local function.
106
39) Should a function contain a return statement if it does not return a value?
In C, void functions does not return anything. So it is useless to put a return statement at the end of
the function, where the control will any way return to the caller function. But, if you want to omit some
portion of the function depending upon the scenario, then this return statement is perfect to avoid
further execution of that void function.
An array can be passed to a function by value, by keeping a parameter with an array tag with empty
square brackets(like []). From the caller function, just pass the array tag. For instance,
...
int k[10];
41) Is it possible to execute code even after the program exits the main() function?
There is a standard C function named atexit() for this purpose that can be used to perform some
operations when your program exiting. You can register some functions with atexit() to be executed
at the time of termination. Here's an example:
#include <stdio.h>
#include <stdlib.h>
void _some_FUNC_(void);
...
atexit(_some_FUNC_);
….
107
}
In C, when some function is called, the parameters are put at the top of the stack. Now the order in
which they are put is the order in which the parameters are parsed. Normally, the order is right to left.
That is, the right most is parsed first and the left most parameter is parsed at last.
If you want to alter this paradigm, then you have to define the function with PASCAL as following:
Here, the left most parameter(int) will be parsed first, then char* and then long.
43) Why does PASCAL matter? Is there any benefit to using PASCAL functions?
The main reason behind using PASCAL is that, in the left-to-right parsing the efficiency of switching
increases in C.
No. They are not the same. Return statement returns control to the caller function, that is, it exits from
the lowest level of the call stack. Where as, exit statement make the program returns to the system
from where the application was started. So, exit always exits from the highest level of call stack.
Eventually, if there is only one level of function call then they both do the same.
45) Point out the error in the program given below, if any ?
main()
int a=10,b;
printf("\n%d",b);
A value is required in function main(). The second assignment should be written in parenthesis as
follows:
108
a>= 5 ? b=100 : (b=200);
main()
const int x;
x = 128;
printf("%d",x);
47) In C, what is the difference between a static variable and global variable?
A static variable ia declared outside of any function and it is accessible only to all the functions
defined in the same file (as the static variable). In case of global variable, it can be accessed by any
function (including the ones from different files).
48) Write a c program to print Hello world without using any semicolon.
void main()
if(printf("Hello world"))
Same way, while and switch statements can be used to achieve this.
49) Write a C program to swap two variables without using third variable ?
109
#include<stdio.h>
int main()
int a=5,b=10;
a=b+a;
b=a-b;
a=a-b;
printf("a= %d b= %d",a,b);
If any pointer is pointing at the memory location/address of any variable, but if the variable is deleted
or does not exist in the current scope of code, while pointer is still pointing to that memory location,
then the pointer is called dangling pointer. For example,
#include<stdio.h>
int *func();
int main()
int *ptr;
ptr=func();
printf("%d",*ptr);
return 0;
110
}
int * func()
int x=18;
return &x;
Output is Garbage value, since the variable x has been freed as soon as the function func() returned
A pointer is known as wild pointer c, if it has not been initialized. For Example:
int main()
int *ptr;
printf("%u\n",ptr);
printf("%d",*ptr);
return 0;
Here ptr is wild pointer, because it has not been initialized. Wild pointer is not the same as NULL
pointer. Because, NULL pointer doesn't point to any location, but a wild pointer points to a specific
memory location but the memory may not be available for current application, which is very fatal.
111
Declaration of function is known as prototype of a function. Prototype says the name, parameter list
and return type of a function but not the definition, this is same as declaring some variable but not
defining it. For example,
53) Write a c program to find size of structure without using sizeof operator?
struct XXX
int x;
float y;
char z;
};
int main()
ptr++;
return 0;
Size of all pointers are same in C, regardless of their type because pointers variable holds a memory
location. And for a given system, this size is constant. The type of pointer is used to know the size of
the data that the pointer is pointer is pointing to.
int main()
int a = 260;
char *ptr;
printf("%d ",*ptr);
return 0;
(A) 2 (B) 260 (C) 4 (D) Compilation error (E) None of above
Answer is B. 260 will take two byte memory space to reside and the bytes will be 1 and 4. Binary
value of 260 is 00000001 00000100 (In 16 bit). So, ptr is only pointing to first 8 bit whose decimal
value is 4.
#include "stdio.h"
int main()
char arr[100];
return 1;
113
The scanf returns the number of inputs it has successfully read, so the output will be 1.
#include <stdio.h>
int main()
return 0;
The printf is a library function which takes a char pointer as input. Here the pointer in incremented by
6, so the pointer will advance from pointing 'H' to 'W'. So the output will be “World”.
#include <stdio.h>
int main()
return 0;
In C, X[5] and 5[X] are the same. Here, 6[“Hello World”] will return the 6th element of the array “Hello
World”, that is 'W'.
#include <stdio.h>
main()
114
{
char *p = 0;
*p = 'a';
a) It will print a b) It will print 0 c) Compile time error d) Run time error
Answer is d, runtime error. Because the pointer p is declared, but not the variable it is pointing to. In
the statement, while assigning 'a', it will try to write in the address 0 and will get runtime error.
(A) gets() can read a string with newline chacters but a normal scanf() with %s can not.
(B) gets() can read a string with spaces but a normal scanf() with %s can not.
(C) gets() can always replace scanf() without any additional code.
(D) None of the above
Ans: (B)
#include<stdio.h>
int main()
return 0;
Answer is 12344. 1234 will be printed by the second printf and it will return 4 as printf returns the
number of letters it printed.
To set up “pf” to point to the strcmp() function, you want a declaration that looks just like
the strcmp()function's declaration, but that has *pf rather than strcmp:
Pointers to functions are interesting, when you pass them to other functions. A function that takes
function pointers says, in effect, "Part of what I do can be customized. Give me a pointer to a function,
and I'll call it when that part of the job needs to be done. That function can do its part for me. This is
known as a callback". It's used a lot in graphical user interface libraries, in which the style of a display
is built into the library but the contents of the display are part of the application.
65) How to return two variables of different data type from a function?
struct STRUCTURE
int integerVar;
char characterVar;
};
STRUCTURE Function()
STRUCTURE x;
return (x);
116
66) What is the difference between far pointer and near pointer ?
Near pointers are 16 bits long and can address a 64KB range. Far pointers are 32 bits long and can
address a 1MB range. Near pointers operate within a 64KB segment. There's one segment for
function addresses and one segment for data.
Far pointers have a 16-bit base (the segment address) and a 16-bit offset. The base is multiplied by
16, so a far pointer is effectively 20 bits long. For example, if a far pointer had a segment of 0x7000
and an offset of 0x1224, the pointer would refer to address 0x71224. A far pointer with a segment of
0x7122 and an offset of 0x0004 would refer to the same address.
Sometimes, you can get away with using a small memory model in most of a given program.
Somethings may not fit in your small data and code segments.
When that happens, you can use explicit far pointers and function declarations to get at the rest of
memory. A far function can be outside the 64KB segment, most functions are shoehorned into for a
small-code model. (Often, libraries are declared explicitly far, so they'll work no matter what code
model the program uses.)
A far pointer can refer to information outside the 64KB data segment. Typically, such pointers are
used with farmalloc() and such, to separately manage a heap from the rest of the data.
char *x;
if (*y != NULL)
(*y)++;
x = *y;
else
117
{
(*z)++;
x = *z;
69) Write a C program to print a semicolon without using any semicolon in the whole
program?
#include<stdio.h>
#define SEMICOLON 59
void main()
if(printf("%c",SEMICOLON))
70) How can you determine the size of an allocated portion of memory?
You can't. free() can, but there's no way for a program to know the use of method free()
71) Add your code in the program so that the given code block print 'unknown' ?
if(a>10) printf("greater");
118
else if(a==10) printf("equal");
else printf("unknown");
#define a b++
main()
int b = 10;
if(a>10) printf("greater");
else printf("unknown");
No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By
definition, if you have a void pointer, you don't know what it's pointing to, so you don't know the size of
what it's pointing to. If you want pointer arithmetic to work on raw addresses, use character pointers.
There is no fixed guideline or limit to the number of parameters your functions can have. However, it
is considered bad programming style for your functions to contain an abnormally high (eight or more)
119
number of parameters. The number of parameters a function has also directly affects the speed at
which it is called - the more parameters, the slower the function call.
No. The exit() function is used to exit your program and return control to the operating system. The
return statement is used to return from a function and return control to the calling function. If you
issue a return from the main() function, you are essentially returning control to the calling function,
which is the operating system. In this case, the return statement and exit() function are similar.
It's valid to address it, but not to see what's there. (The really short answer is, "Yes, so don't worry
about it.") With most compilers, if you say
int i, a[MAX], j;
Then either i or j is at the part of memory just after the last element of the array. The way to see
whether i or j follows the array is to compare their addresses with that of the element following the
array. The way to say this in C is that either
is true or
EMBEDDED C
The C's volatile keyword is a qualifier that tells the compiler not to optimize when applied to a
variable. By declaring a variable volatile, we can tell the compiler that the value of the variable may
change any moment from outside of the scope of the program. A variable should be declared volatile
whenever its value could change unexpectedly and beyond the comprehension of the compiler.
In those cases it is required not to optimize the code, doing so may lead to erroneous result and load
the variable every time it is used in the program. Volatile keyword is useful for memory-mapped
peripheral registers, global variables modified by an interrupt service routine, global variables
accessed by multiple tasks within a multi-threaded application.
120
The const keyword make sure that the value of the variable declared as const can't be changed. This
statement holds true in the scope of the program. The value can still be changed by outside
intervention. So, the use of const with volatile keyword makes perfect sense.
If we see the declaration volatile int *p, it means that the pointer itself is not volatile and points to an
integer that is volatile. This is to inform the compiler that pointer p is pointing to an integer and the
value of that integer may change unexpectedly even if there is no code indicating so in the program.
The NULL is a macro defined in C. Null pointer actually means a pointer that does not point to any
valid location. We define a pointer to be null when we want to make sure that the pointer does not
point to any valid location and not to use that pointer to change anything. If we don't use null pointer,
then we can't verify whether this pointer points to any valid location or not.
The void pointer means that it points to a variable that can be of any type. Other pointers points to a
specific type of variable while void pointer is a somewhat generic pointer and can be pointed to any
data type, be it standard data type(int, char etc) or user define data type (structure, union etc.). We
can pass any kind of pointer and reference it as a void pointer. But to dereference it, we have to type
the void pointer to correct data type.
7) What is ISR?
An ISR(Interrupt Service Routine) is an interrupt handler, a callback subroutine which is called when
a interrupt is encountered.
ISR does not return anything. An ISR returns nothing because there is no caller in the code to read
the returned values.
121
Interrupt latency can be minimized by writing short ISR routine and by not delaying interrupts for more
time.
We can use function inside ISR as long as that function is not invoked from other portion of the code.
12) Can we use printf inside ISR?
Printf function in ISR is not supported because printf function is not reentrant, thread safe and uses
dynamic memory allocation which takes a lot of time and can affect the speed of an ISR up to a great
extent.
Putting a break point inside ISR is not a good idea because debugging will take some time and a
difference of half or more second will lead to different behavior of hardware. To debug ISR, definitive
logs are better.
A static variable cannot be declared without defining it. A static variable can be defined in the header
file. But doing so, the result will be having a private copy of that variable in each source file which
includes the header file. So it will be wise not to declare a static variable in header file, unless you are
dealing with a different scenario.
Count down to zero loops are better. Reason behind this is that at loop termination, comparison to
zero can be optimized by the compiler. Most processors have instruction for comparing to zero. So
they don't need to load the loop variable and the maximum value, subtract them and then compare to
zero. That is why count down to zero loop is better.
The ARM compilers support inline functions with the keyword __inline. These functions have a small
definition and the function body is substituted in each call to the inline function. The argument passing
and stack maintenance is skipped and it results in faster code execution, but it increases code size,
particularly if the inline function is large or one inline function is used often.
Yes. Include files can be nested any number of times. But you have to make sure that you are not
including the same file twice. There is no limit to how many header files that can be included. But the
number can be compiler dependent, since including multiple header files may cause your computer to
run out of stack memory.
122
Static keyword can be used with variables as well as functions. A variable declared static will be of
static storage class and within a function, it maintains its value between calls to that function. A
variable declared as static within a file, scope of that variable will be within that file, but it can't be
accessed by other files.
Functions declared static within a module can be accessed by other functions within that module.
That is, the scope of the function is localized to the module within which it is declared.
Volatile keyword is used to prevent compiler to optimize a variable which can change unexpectedly
beyond compiler's comprehension. Suppose, we have a variable which may be changed from scope
out of the program, say by a signal, we do not want the compiler to optimize it. Rather than optimizing
that variable, we want the compiler to load the variable every time it is encountered. If we declare a
variable volatile, compiler will not cache it in its register.
Sometimes to handle an interrupt, a substantial amount of work has to be done. But it conflicts with
the speed need for an interrupt handler. To handle this situation, Linux splits the handler into two
parts – Top half and Bottom half. The top half is the routine that actually responds to the interrupt.
The bottom half on the other hand is a routine that is scheduled by the upper half to be executed later
at a safer time.
All interrupts are enabled during execution of the bottom half. The top half saves the device data into
the specific buffer, schedules bottom half and exits. The bottom half does the rest. This way the top
half can service a new interrupt while the bottom half is working on the previous.
RISC (Reduced Instruction Set Computer) could carry out a few sets of simple instructions
simultaneously. Fewer transistors are used to manufacture RISC, which makes RISC cheaper. RISC
has uniform instruction set and those instructions are also fewer in number. Due to the less number of
instructions as well as instructions being simple, the RISC computers are faster. RISC emphasise on
software rather than hardware. RISC can execute instructions in one machine cycle.
CISC (Complex Instruction Set Computer) is capable of executing multiple operations through a
single instruction. CISC have rich and complex instruction set and more number of addressing
modes. CISC emphasise on hardware rather that software, making it costlier than RISC. It has a
small code size, high cycles per second and it is slower compared to RISC.
123
To meet real time requirements, the behaviour of the scheduler must be predictable. This type of OS
which have a scheduler with predictable execution pattern is called Real Time OS(RTOS). The
features of an RTOS are
23) What is the difference between hard real-time and soft real-time OS?
A Hard real-time system strictly adheres to the deadline associated with the task. If the system fails to
meet the deadline, even once, the system is considered to have failed. In case of a soft real-time
system, missing a deadline is acceptable. In this type of system, a critical real-time task gets priority
over other tasks and retains that priority until it completes.
RTOS uses pre-emptive scheduling. In pre-emptive scheduling, the higher priority task can interrupt a
running process and the interrupted process will be resumed later.
If two tasks share a resource, the one with higher priority will run first. However, if the lower-priority
task is using the shared resource when the higher-priority task becomes ready, then the higher-
priority task must wait for the lower-priority task to finish. In this scenario, even though the task has
higher priority it needs to wait for the completion of the lower-priority task with the shared resource.
This is called priority inversion.
Priority inheritance is a solution to the priority inversion problem. The process waiting for any
resource which has a resource lock will have the maximum priority. This is priority inheritance. When
one or more high priority jobs are blocked by a job, the original priority assignment is ignored and
execution of critical section will be assigned to the job with the highest priority in this elevated
scenario. The job returns to the original priority level soon after executing the critical section.
Pipes
Named pipes or FIFO
Semaphores
Shared memory
Message queue
124
Socket
Semaphore is actually a variable or abstract data type which controls access to a common resource
by multiple processes. Semaphores are of two types -
Binary semaphore – It can have only two values (0 and 1). The semaphore value is set to 1 by the
process in charge, when the resource is available.
Counting semaphore – It can have value greater than one. It is used to control access to a pool of
resources.
If a resource is locked, a thread that wants to access that resource may repetitively check whether
the resource is available. During that time, the thread may loop and check the resource without doing
any useful work. Suck a lock is termed as spin lock.
Mutual exclusion and synchronization can be used by binary semaphore while mutex is used only for
mutual exclusion.
A mutex can be released by the same thread which acquired it. Semaphore values can be changed
by other thread also.
From an ISR, a mutex can not be used.
The advantage of semaphores is that, they can be used to synchronize two unrelated processes
trying to access the same resource.
Semaphores can act as mutex, but the opposite is not possible.
Virtual memory is a technique that allows processes to allocate memory in case of physical memory
shortage using automatic storage allocation upon a request. The advantage of the virtual memory is
that the program can have a larger memory than the physical memory. It allows large virtual memory
to be provided when only a smaller physical memory is available. Virtual memory can be
implemented using paging.
A paging system is quite similar to a paging system with swapping. When we want to execute a
process, we swap it into memory. Here we use a lazy swapper called pager rather than swapping the
entire process into memory. When a process is to be swapped in, the pager guesses which pages will
be used based on some algorithm, before the process is swapped out again. Instead of swapping
whole process, the pager brings only the necessary pages into memory. By that way, it avoids
reading in unnecessary memory pages, decreasing the swap time and the amount of physical
memory.
Passing structure by its value to a function is possible, but not a good programming practice. First of
all, if we pass the structure by value and the function changes some of those values, then the value
change is not reflected in caller function. Also, if the structure is big, then passing the structure by
value means copying the whole structure to the function argument stack which can slow the program
by a significant amount.
In C, the array name itself represents the address of the first element. So, even if we pass the array
name as argument, it will be passed as reference and not its address.
The advantage of the macro and inline function is that the overhead for argument passing and stuff is
reduced as the function are in-lined. The advantage of macro function is that we can write type
insensitive functions. It is also the disadvantage of macro function as macro functions can't do
validation check. The macro and inline function also increases the size of the executable.
Inlining an recursive function reduces the overhead of saving context on stack. But, inline is merely a
suggestion to the compiler and it does not guarantee that a function will be inlined. Obviously, the
compiler won't be able to inline a recursive function infinitely. It may not inline it at all or it may inline it,
just a few levels deep.
37) #define cat(x,y) x##y concatenates x to y. But cat(cat(1,2),3) does not expand but gives
preprocessor warning. Why?
The cat(x, y) expands to x##y. It just pastes x and y. But in case of cat(cat(1,2),3), it expands to
cat(1,2)##3 instead of 1##2##3. That is why it is giving preprocessor warning.
39) Declare a manifest constant that returns the number of seconds in a year using
preprocessor? Disregard leap years in your answer.
126
#define SECONDS_IN_YEAR (60UL * 60UL * 24UL * 365UL)
Do not forget to use UL, since the output will be very big integer.
40) Using the variable a, write down definitions for the following:
An integer
A pointer to an integer
A pointer to a pointer to an integer
An array of ten integers
An array of ten pointers to integers
A pointer to an array of ten integers
A pointer to a function that takes an integer as an argument and returns an integer
Pass an array of ten pointers to a function that take an integer argument and return an integer.
int a;
int *a;
int **a;
int a[10];
int *a[10];
int (*a)[10];
int (*a)(int);
int (*a[10])(int);
If you have problem understanding these, please read pointer section in the provide tutorial
thoroughly.
41) Consider the two statements below and point out which one is preferred and why?
#define B struct A *
typedef struct A * C;
The typedef is preferred. Both statements declare pointer to struct A to something else and in one
glance both looks fine. But there is one issue with the define statement. Consider a situation where
we want to declare p1 and p2 as pointer to struct A. We can do this by -
C p1, p2;
But doing - B p1, p2, it will be expanded to struct A * p1, p2. It means that p1 is a pointer to struct A
but p2 is a variable of struct A and not a pointer.
127
char *ptr;
else
The output will be “Got a valid pointer”. It is because malloc(0) returns a valid pointer, but it allocates
size 0. So this pointer is of no use, but we can use this free pointer and the program will not crash.
The const keyword when used in c means that the value of the variable will not be changed. But the
value of the variable can be changed using a pointer. The const identifier can be used like this -
Both means the same and it indicates that a is an constant integer. But if we declare something like
this -
const int *p
then it does not mean that the pointer is constant but rather it is pointing to an constant integer. The
declaration of an const pointer to a non-constant integer will look like this -
int * cont p;
const int a;
int const a;
45) How to decide whether given processor is using little endian format or big endian format ?
The following program can find out the endianness of the processor.
#include<stdio.h>
main ()
union Test
unsigned int i;
};
else
129
46) What is the concatenation operator?
The Concatenation operator (##) in macro is used to concatenate two arguments. Literally, we can
say that the arguments are concatenated, but actually their value are not concatenated. Think it this
way, if we pass A and B to a macro which uses ## to concatenate those two, then the result will be
AB. Consider the example to clear the confusion-
#define SOME_MACRO(a, b) a##b
main()
47) Infinite loops often arise in embedded systems. How does you code an infinite loop in C?
There are several ways to code an infinite loop -
while(1)
{}
or,
for(;;)
{}
or,
Loop:
goto Loop
But many programmers prefer the first solution as it is easy to read and self-explanatory, unlike the
second or the last one.
130
main()
fork();
fork();
fork();
printf("hello world\n");
It will print “hello world' 8 times. The main() will print one time and creates 3 children, let us say
Child_1, Child_2, Child_3. All of them printed once. The Child_3 will not create any child. Child2 will
create one child and that child will print once. Child_1 will create two children, say Child_4 and
Child_5 and each of them will print once. Child_4 will again create another child and that child will
print one time. A total of eight times the printf statement will be executed.
Forward Referencing with respect to pointers is used when a pointer is declared and compiler
reserves the memory for the pointer, but the variable or data type is not defined to which the pointer
points to. For example
struct A *p;
struct A
// members
};
50) How is generic list manipulation function written which accepts elements of any kind?
It can be achieved using void pointer. A list may be expressed by a structure as shown below
typedef struct
node *next;
/* data part */
131
......
}node;
typedef struct
node *next;
void *data;
}node;
This way, the generic manipulation function can work on this type of structures.
51) How can you define a structure with bit field members?
char c1 : 3;
char c2 : 4;
char c3 : 1;
};
Here c1, c2 and c3 are members of a structure with width 3, 4, and 1 bit respectively. The ':' indicates
that they are bit fields and the following numbers indicates the width in bits.
52) How do you write a function which takes 2 arguments - a byte and a field in the byte and
returns the value of the field in that byte?
The function will look like this -
int GetFieldValue(int byte, int field )
132
return byte;
The byte is right shifted exactly n times where n is same as the field value. That way, our intended
value ends up in the 0th bit position. "Bitwise And" with 1 can get the intended value. The function
then returns the intended value.
53) Which parameters decide the size of data type for a processor ?
Actually, compiler is the one responsible for size of the data type. But it is true as long as OS allows
that. If it is not allowable by OS, OS can force the size.
The preprocessor commands are processed and expanded by the preprocessor before actual
compilation. After preprocessing, the compiler takes the output of the preprocessor and the source
code, and generates assembly code. Once compiler completes its work, the assembler takes the
assembly code and produces an assembly listing with offsets and generate object files.
The linker combines object files or libraries and produces a single executable file. It also resolves
references to external symbols, assigns final addresses to functions and variables, and revises code
and data to reflect new addresses.
55) What is the difference between static linking and dynamic linking ?
In static linking, all the library modules used in the program are placed in the final executable file
making it larger in size. This is done by the linker. If the modules used in the program are modified
after linking, then re-compilation is needed. The advantage of static linking is that the modules are
present in an executable file. We don't want to worry about compatibility issues.
In case of dynamic linking, only the names of the module used are present in the executable file and
the actual linking is done at run time when the program and the library modules both are present in
the memory. That is why, the executables are smaller in size. Modification of the library modules used
does not force re-compilation. But dynamic linking may face compatibility issues with the library
modules used.
Preprocessor error is used to throw a error message during compile time. We can check the sanity of
the make file and using debug options given below
#ifndef DEBUG
#ifndef RELEASE
#endif
57) On a certain project it is required to set an integer variable at the absolute address 0x67a9
to the value 0xaa55. The compiler is a pure ANSI compiler. Write code to accomplish this task.
int *ptr;
*ptr = 0xaa55;
The watchdog timer is a timing device with a predefined time interval. During that interval, some event
may occur or else the device generates a time out signal. It is used to reset to the original state
whenever some inappropriate events take place which can result in system malfunction. It is usually
operated by counter devices.
The expression ++n requires a single machine instruction such as INR to carry out the increment
operation. In case of n+1, apart from INR, other instructions are required to load the value of n. That
is why ++n is faster.
A pointer that is not initialized to any valid address or NULL is considered as wild pointer. Consider
the following code fragment -
int *p;
*p = 20;
Here p is not initialized to any valid address and still we are trying to access the address. The p will
get any garbage location and the next statement will corrupt that memory location.
If a pointer is de-allocated or freed and the pointer is not assigned to NULL, then it may still contain
that address and accessing the pointer means that we are trying to access that location and it will
give an error. This type of pointer is called dangling pointer.
134
62) Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ?
We know that a[i] can be written as *(a+i). Same way, the array elements can be written like pointer
expression as follows -
a[i][j] == *(*(a+i)+j)
a[i][j][k] == *(*(*(a+i)+j)+k)
a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l)
63) Which bit wise operator is suitable for checking whether a particular bit is on or off?
"Bitwise And" (&) is used to check if any particular bit is set or not. To check whether 5'th bit is set we
can write like this
Here, shifting byte by 4 position means taking 5'th bit to first position and "Bitwise And" will get the
value in 0 or 1.
The register modifier is used when a variable is expected to be heavily used and keeping it in the
CPU’s registers will make the access faster.
The string function strcat( ) concatenates two strings. But here the second argument is '!', a character
and that is the reason why the code doesn't work. To make it work, the code should be changed like
this:
void main()
135
int const * p = 5;
printf("%d",++(*p));
The above program will result in compilation error stating “Cannot modify a constant value”. Here p is
a pointer to a constant integer. But in the next statement, we are trying to modify the value of that
constant integer. It is not permissible in C and that is why it will give a compilation error.
#include<stdio.h>
main()
unsigned int a = 2;
int b = -10;
If you have guessed the answer wrong, then here is the explanation for you. The a + b is -8, if we do
the math. But here the addition is between different integral types - one is unsigned int and another is
int. So, all the operands in this addition are promoted to unsigned integer type and b turns to a
positive number and eventually a big one. The outcome of the result is obviously greater than 0 and
hence, this is the output.
68) Write a code fragment to set and clear only bit 3 of an integer.
int a;
void SetBit3()
a |= BIT(3);
}
136
void ClearBit3()
a &= ~BIT(3);
return *p * *p;
The intention of the above code is to return the square of the integer pointed by the pointer p. Since it
is volatile, the value of the integer may have changed suddenly and will result in something else
which will looks like the result of the multiplication of two different integers. To work as expected, the
code needs to be modified like this.
int a = *p;
return a*a;
70) Is the code fragment given below is correct? If so what is the output?
int i = 2, j = 3, res;
res = i+++j;
The above code is correct, but little bit confusing. It is better not to follow this type of coding style. The
compiler will interpret above statement as “res = i++ + j”. So the res will get value 5 and i after this will
be 3.
137
ADVANCE C
The ideal form of printf is printf("%d",x); where x is an integer variable. Executing this statement will
print the value of x. But here, there is no variable is provided after %d so compiler will show garbage
value. The reason is a bit tricky.
When access specifiers are used in printf function, the compiler internally uses those specifiers to
access the arguments in the argument stack. In ideal scenario compiler determines the variable offset
based on the format specifiers provided. If we write printf("%d", x) then compiler first accesses the
first specifier which is %d and depending on the that the offset of variable x in the memory is
calculated. But the printf function takes variable arguments.
The first argument which contains strings to be printed or format specifiers is mandatory. Other than
that, the arguments are optional.So, in case of only %d used without any variable in printf, the
compiler may generate warning but will not cause any error. In this case, the correct offset based on
%d is calculated by compiler but as the actual data variable is not present in that calculated location
of memory, the printf will fetch integer size value and print whatever is there (which is garbage value
to us).
The printf function upon successful return, returns the number of characters printed in output device.
So, printf(“A”) will return 1. The scanf function returns the number of input items successfully matched
and assigned, which can be fewer than the format specifiers provided. It can also return zero in case
of early matching failure.
If the pointer holding that memory address is passed to realloc with size argument as zero (like
realloc(ptr, 0)) the the memory will be released.
There are no escape sequence provided for '%' in C. To print '%' one should use '%%', like -
Ans: According to man page “the number of characters written so far is stored into the integer.
indicated by the int * (or variant) pointer argument.“. Meaning if we use it in printf, it will get the
number of characters already written until %n is encountered and this number will stored in the
variable provided. The variable must be an integer pointer.
138
#include<stdio.h>
main()
int c;
printf("%d", c);
#include <stdio.h>
main()
int a = 6;
int b = 10;
a = a + b;
b = a - b;
a = a - b;
#include <stdio.h>
main()
139
int a = 6;
int b = 10;
a ^= b;
b ^= a;
a ^= b;
7) Consider the two structures Struct A and Struct B given below. What will be size of these
structures?
struct A
{
unsigned char c1 : 3;
unsigned char c2 : 4;
unsigned char c3 : 1;
}a;
struct A
{
unsigned char c1 : 3;
unsigned char : 0;
unsigned char c2 : 4;
unsigned char c3 : 1;
}a;
The size of the structures will be 1 and 2. In case of first structure, the members will be assigned a
byte as follows -
7 6 5 4 3 2 1 0
c3 c2 c2 c2 c2 c1 c1 c1
8 7 6 5 4 3 2 1 0
140
c3 c2 c2 c2 c2 c1 c1 c1
The :0 field (0 width bit field) forces the next bit width member assignment to start from the next
nibble. By doing so, the c3 variable will be assigned a bit in the next byte, resulting the size of the
structure to 2.
To call a function pragma startup directive should be used. Pragma startup can be used like this -
void fun()
printf(“In fun\n”);
main()
printf(“In main\n”);
In fun
In main
But this pragma directive is compiler dependent. Gcc does not support this. So, it will ignore the
startup directive and will produce no error. But the output in that case will be -
In main
You can think lvalue as a left side operant in an assignment and rvalue is the right. Also, you can
remember lavlue as location. So, the lvalue means a location where you can store any value. Say, for
141
statement i = 20, the value 20 is to be stored in the location or address of the variable i. 20 here is
rvalue. Then the 20 = I, statement is not valid. It will result in compilation error “lvalue required” as 20
does not represent any location.
char c;
int i;
}B;
#pragma pack(1)
typedef struct A
char c;
int I;
}B;
In both cases the size of the structure will be 5. But remember, the pragma pack and the other
method mentioned, both are compiler dependent.
int i = atoi(str);
142
Method 2:
#include <stdio.h>
main()
int i = 3;
switch(i)
default:
printf("%d", i);
case 1:
printf("1\n");
case 2:
printf("2\n");
case 3:
143
printf("3\n");
Output of this program will be 3. The position of the default is before case 1. So, even if there is no
break after case 3, the execution will just exit switch case and it will not go to default case.
13) How to prevent same header file getting included multiple times?
We can use ifndef and define preprocessors. Say the header file is hdrfile.h, then we can write the
header file like -
#ifndef _HDRFILE_H_
#define _HDRFILE_H_
#endif
The ifndef will check whether macro HDRFILE_H_ is defined or not. If it is not defined, it will define
the macro. From next time onward the statements inside ifndef will not be included.
Enum values can be automatically generated by compiler if we let it. But all the define values are to
be mentioned specifically.
Macro is preprocessor, so unlike enum which is a compile time entity, source code has no idea about
these macros. So, the enum is better if we use a debugger to debug the code.
If we use enum values in a switch and the default case is missing, some compiler will give a warning.
Enum always makes identifiers of type int. But the macro let us choose between different integral
types.
Macro does not specifically maintain scope restriction unlike enum. For example -
#include <stdio.h>
main()
#define A 10
144
printf("first A: %d\n", A);
first A: 10
second A: 10
#include<stdio.h>
main()
char *p = "Pointers";
p[2] = 'z';
printf("%c", *p);
The program will crash. The pointer p points to string “Pointers”. But the string in constant and C will
not allow to change its values. Forcibly doing so, like we did it, will cause crash of the program.
---------------------------------------------------------------------------------------------------------------------------------------
145
THANK - YOU
146