100% found this document useful (6 votes)
2K views147 pages

C Programming Complete Notes

C is a general-purpose programming language developed in the 1970s to write operating systems. It produces efficient, low-level programs and can be compiled on many platforms. C was used to write UNIX and is widely used for system programming tasks like operating systems, language compilers, databases, and utilities. The document provides an overview of C programming basics including data types, variables, operators, and program structure.

Uploaded by

Aishwary Angadi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (6 votes)
2K views147 pages

C Programming Complete Notes

C is a general-purpose programming language developed in the 1970s to write operating systems. It produces efficient, low-level programs and can be compiled on many platforms. C was used to write UNIX and is widely used for system programming tasks like operating systems, language compilers, databases, and utilities. The document provides an overview of C programming basics including data types, variables, operators, and program structure.

Uploaded by

Aishwary Angadi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 147

C PROGRAMMING 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 does not allow punctuation characters such as @, $, and % within identifiers.

C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C.
Here are some examples of acceptable identifiers −

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal

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.

auto else Long switch


break enum Register typedef
case extern Return union
char float Short unsigned
const for Signed void
continue goto Sizeof volatile
default if Static while
2
do int Struct _Packed
double

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 −

Storage size for int : 4

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

10 = 20; // invalid statement; would generate compile-time error

C - Constants and Literals


Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called
literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. Constants are treated just like regular variables except that their values cannot be modified
after their definition.

Defining Constants
There are two simple ways in C to define constants −

#define preprocessor. #define identifier value

 Using const keyword.

You can use const prefix to declare constants with a specific type as follows −

const type variable = value;


Note that it is a good programming practice to define constants in CAPITALS.

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 −

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

 Assume A = 60 and B = 13 in binary format, they will be as follows −


 A = 0011 1100
 B = 0000 1101
 -----------------
 A&B = 0000 1100
 A|B = 0011 1101
 A^B = 0011 0001
 ~A = 1100 0011
 The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −

Operator Description Example


Binary AND Operator copies a bit to the result if it exists in
& (A & B) = 12, i.e., 0000 1100
both operands.
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, i.e., 0011 1101
operand.
Binary XOR Operator copies the bit if it is set in one
^ (A ^ B) = 49, i.e., 0011 0001
operand but not both.
Binary Ones Complement Operator is unary and has the (~A ) = -60, i.e,. 1100 0100 in 2's
~
effect of 'flipping' bits. complement form.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the right A << 2 = 240 i.e., 1111 0000
operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the right A >> 2 = 15 i.e., 0000 1111
operand.

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

Misc Operators ↦ sizeof & ternary


 Besides the operators discussed above, there are a few other important operators including sizeof and ? :
supported by the C Language.

Operator Description Example


sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
* Pointer to a variable. *a;
If Condition is true ? then value X : otherwise value
?: Conditional Expression.
Y

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.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
+ - ! ~ ++ - -
Unary Right to left
(type)* & sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
= += -= *= /=
Assignment %=>>= <<= &= Right to left
^= |=
Comma , Left to right
The ? : Operator-----We have covered conditional operator ? :
in the previous chapter which can be used to replace if...else statements. It
has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement
of the colon.

The value of a ? expression is determined like this −

 Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes


the value of the entire ? expression.
 If Exp1 is false, then Exp3 is evaluated and its value becomes the
value of the expression.

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) {

/* statement(s) will execute if the boolean expression is true */


} else {
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be
executed.

#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

If...else if...else Statement


Syntax

The syntax of an if...else if...else statement in C programming language is −

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) {

/* Executes when the boolean expression 1 is true */


if(boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
}

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 */

/* you can have any number of case statements */


default : /* 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 () {

/* local variable definition */


char grade = 'B';

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" );
}

printf("Your grade is %c\n", grade );

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

C - nested switch statements


switch as a part of the statement sequence of an outer switch. inner and outer switch contain common values, no
conflicts will arise.

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 () {

/* local variable definition */


int a = 100;
int b = 200;

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 );
}
}

printf("Exact value of a is : %d\n", a );


printf("Exact value of b is : %d\n", b );

return 0;
}

14
When the above code is compiled and executed, it produces the following result −

This is part of outer switch


This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

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 −

for ( init; condition; increment ) {


statement(s);
}

Here is the flow of control in a 'for' loop −

 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;

/* for loop execution */


for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", 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 −

for ( init; condition; increment ) {

for ( init; condition; increment ) {


statement(s);
}
statement(s);
}

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 () {

/* local variable definition */


int i, j;

for(i = 2; i<100; i++) {

for(j = 2; j <= (i/j); j++)


if(!(i%j)) break; // if factor found, not prime
19
if(j > (i/j)) printf("%d is prime\n", i);
}

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

Loop Control Statements


Loop control statements change execution from its normal sequence.

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 () {

/* local variable definition */


int a = 10;

/* while loop execution */


while( a < 20 ) {

printf("value of a: %d\n", a);


a++;

if( a > 15) {


/* terminate the loop using break statement */
break;
}
}

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 () {

/* local variable definition */


int a = 10;

/* do loop execution */
do {

if( a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}

printf("value of a: %d\n", a);


a++;

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 () {

/* local variable definition */


int a = 10;

/* do loop execution */
LOOP:do {

if( a == 15) {
/* skip the iteration */
a = a + 1;
goto LOOP;
}

printf("value of a: %d\n", a);


a++;

}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

The Infinite Loop


A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose

#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.

NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

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 −

return_type function_name( parameter list ) {


body of the function
}

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.

A function declaration has the following parts −

return_type function_name( parameter list );

Parameter names are not important in function declaration only their type is required, so the following is also a
valid declaration −

int max(int, int);


Function declaration is required when you define a function in one source file and you call that function in another file.
In such case, you should declare the function at the top of the file calling the function.

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 () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

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 −

Max value is : 200

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 −

Function call by Value in C


The call by value method of passing arguments to a function copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to the parameter inside the function have no effect
on the argument.

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.

/* function definition to swap the values */


void swap(int x, int y) {

int temp;

temp = x; /* save the value of x */


x = y; /* put y into x */
y = temp; /* put temp into y */

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 () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */


swap(a, b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}

27
Let us put the above code in a single C file, compile and execute it, it will produce the following result −

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

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.

Function call by reference in C


The call by reference method of passing arguments to a function copies the address of an argument into the
formal parameter. Inside the function, the address is used to access the actual argument used in the call. It
means the changes made to the parameter affect the passed argument.

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.

/* function definition to swap the values */


void swap(int *x, int *y) {

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 () {

/* local variable definition */


int a = 100;
int b = 200;

printf("Before swap, value of a : %d\n", a );


printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.


* &a indicates pointer to a ie. address of variable a and
28
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);

printf("After swap, value of a : %d\n", a );


printf("After swap, value of b : %d\n", b );

return 0;
}

Let us put the above code in a single C file, compile and execute it, to produce the following result −

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

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 −

 Inside a function or a block which is called local variables.


 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal parameters.

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 () {

/* local variable declaration */


int a, b;
int c;

/* 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>

/* global variable declaration */


int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

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>

/* global variable declaration */


int g = 20;

int main () {

/* local variable declaration */


int g = 10;

printf ("value of g = %d\n", g);

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>

/* global variable declaration */


int a = 20;

int main () {

/* local variable declaration in main function */


int a = 10;
int b = 20;
int c = 0;

printf ("value of a in main() = %d\n", a);


c = sum( a, b);
printf ("value of c in main() = %d\n", c);

return 0;
}

/* function to add two integers */


int sum(int a, int b) {

printf ("value of a in sum() = %d\n", a);


printf ("value of b in sum() = %d\n", b);

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

Initializing Local and Global Variables


When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global
variables are initialized automatically by the system when you define them as follows −

Data Type Initial Default Value


int 0
char '\0'
31
float 0
double 0
pointer NULL

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];

Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

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 −

double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

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 −

Accessing Array Elements


An element is accessed by indexing the array name. This is done by placing the index of the element within
square brackets after the name of the array. For example −

double salary = balance[9];

The above statement will take the 10th element from the array and assign the value to salary variable.

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */


int i,j;

/* initialize elements of array n to 0 */


for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}

/* output each array element's value */


for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}

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'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row has 4 columns.

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 a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


34
An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of
the array. For example −

int val = a[2][3];


#include <stdio.h>

int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

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

Passing Arrays as Function Arguments in C

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 −

void myFunction(int *param) {


.
.
.

35
}

Way-2
Formal parameters as a sized array −

void myFunction(int param[10]) {


.
.
.
}

Way-3
Formal parameters as an unsized array −

void myFunction(int param[]) {


.
.
.
}

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 −

double getAverage(int arr[], int size) {

int i;
double avg;
double sum = 0;

for (i = 0; i < size; ++i) {


sum += arr[i];
}

avg = sum / size;

return avg;
}

Now, let us call the above function as follows −

#include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main () {

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};

36
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf( "Average value is: %f ", avg );

return 0;
}

When the above code is compiled together and executed, it produces the following result −

Average value is: 214.400000

Return array from function in C


C programming does not allow to return an entire array as an argument to a function. However, you can return a
pointer to an array by specifying the array's name without an index.

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>

/* function to generate and return random numbers */


int * getRandom( ) {

static int r[10];


int i;

/* set the seed */


srand( (unsigned)time( NULL ) );

for ( i = 0; i < 10; ++i) {


r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}

return r;
}
37
/* main function to call above defined function */
int main () {

/* a pointer to an int */
int *p;
int i;

p = getRandom();

for ( i = 0; i < 10; i++ ) {


printf( "*(p + %d) : %d\n", i, *(p + i));
}

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 () {

/* an array with 5 elements */


double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;

p = balance;

/* output each array element's value */


printf( "Array values using pointer\n");

for ( i = 0; i < 5; i++ ) {


printf("*(p + %d) : %f\n", i, *(p + i) );
}

printf( "Array values using balance as address\n");

for ( i = 0; i < 5; i++ ) {


printf("*(balance + %d) : %f\n", i, *(balance + i) );
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Array values using pointer


*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000

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];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}

When the above code is compiled and executed, it produces the following result −

Address of var1 variable: bff5a400


Address of var2 variable: bff5a3f6

What are Pointers?


A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable address.
The general form of a pointer variable declaration is −

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 −

int *ip; /* pointer to an integer */


double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

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.

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very frequently. (a) We define
a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address
40
available in the pointer variable. This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand. The following example makes use of these operations −

Live Demo
#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}

When the above code is compiled and executed, it produces the following result −

Address of var variable: bffd8b3c


Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

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 () {

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
}

When the above code is compiled and executed, it produces the following result −

The value of ptr is 0

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 −

if(ptr) /* succeeds if p is not null */


if(!ptr) /* succeeds if p is null */

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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */


42
ptr = var;

for ( i = 0; i < MAX; i++) {

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* move to the next location */


ptr++;
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Address of var[0] = bf882b30


Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200

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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have array address in pointer */


ptr = &var[MAX-1];

for ( i = MAX; i > 0; i--) {

printf("Address of var[%d] = %x\n", i-1, ptr );


printf("Value of var[%d] = %d\n", i-1, *ptr );

/* move to the previous location */


ptr--;
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Address of var[2] = bfedbcd8


43
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10

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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;

/* let us have address of the first element in pointer */


ptr = var;
i = 0;

while ( ptr <= &var[MAX - 1] ) {

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* point to the previous location */


ptr++;
i++;
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Address of var[0] = bfdbcb20


Value of var[0] = 10
Address of var[1] = bfdbcb24
Value of var[1] = 100
Address of var[2] = bfdbcb28
Value of var[2] = 200

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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i;

for (i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, var[i] );
}

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>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {


ptr[i] = &var[i]; /* assign the address of integer. */
}

for ( i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, *ptr[i] );
}

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>

const int MAX = 4;

int main () {

char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};

int i = 0;

for ( i = 0; i < MAX; i++) {


printf("Value of names[%d] = %s\n", i, names[i] );
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

Value of names[0] = Zara Ali


Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

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;

/* take the address of var */


ptr = &var;

/* take the address of ptr using address of operator & */


pptr = &ptr;

/* take the value using pptr */


printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);

return 0;
}

When the above code is compiled and executed, it produces the following result −

Value of var = 3000


Value available at *ptr = 3000
Value available at **pptr = 3000

Passing pointers to functions in C


C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a
pointer type.

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>

void getSeconds(unsigned long *par);

int main () {

unsigned long sec;


getSeconds( &sec );

/* print the actual value */

47
printf("Number of seconds: %ld\n", sec );

return 0;
}

void getSeconds(unsigned long *par) {


/* get the current number of seconds */
*par = time( NULL );
return;
}

When the above code is compiled and executed, it produces the following result −

Number of seconds :1294450468

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 () {

/* an int array with 5 elements */


int balance[5] = {1000, 2, 3, 17, 50};
double avg;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf("Average value is: %f\n", avg );
return 0;
}

double getAverage(int *arr, int size) {

int i, sum = 0;
double avg;

for (i = 0; i < size; ++i) {


sum += arr[i];
}

avg = (double)sum / size;


return avg;
}

When the above code is compiled together and executed, it produces the following result −

Average value is: 214.40000

Return pointer from functions in C


48
We have seen in the last chapter how C programming allows to return an array from a function. Similarly, C
also allows to return a pointer from a function. To do so, you would have to declare a function returning a
pointer as in the following example −

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>

/* function to generate and return random numbers. */


int * getRandom( ) {

static int r[10];


int i;

/* set the seed */


srand( (unsigned)time( NULL ) );

for ( i = 0; i < 10; ++i) {


r[i] = rand();
printf("%d\n", r[i] );
}

return r;
}

/* main function to call above defined function */


int main () {

/* a pointer to an int */
int *p;
int i;

p = getRandom();

for ( i = 0; i < 10; i++ ) {


printf("*(p + [%d]) : %d\n", i, *(p + i) );
}

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."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

If you follow the rule of array initialization then you can write the above statement as follows −

char greeting[] = "Hello";

Following is the memory presentation of the above defined string in C/C++ −

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 () {

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


printf("Greeting message: %s\n", greeting );
return 0;
}

When the above code is compiled and executed, it produces the following result −

Greeting message: Hello

C supports a wide range of functions that manipulate null-terminated strings −

Sr.No. Function & Purpose


strcpy(s1, s2);
1
Copies string s2 into string s1.
strcat(s1, s2);
2
Concatenates string s2 onto the end of string s1.
strlen(s1);
3
Returns the length of string s1.
strcmp(s1, s2);
4
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch);
5
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
6
Returns a pointer to the first occurrence of string s2 in string s1.

The following example uses some of the above-mentioned functions −

Live Demo
#include <stdio.h>
#include <string.h>

int main () {

char str1[12] = "Hello";


char str2[12] = "World";
char str3[12];
int len ;

/* copy str1 into str3 */


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
51
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}

When the above code is compiled and executed, it produces the following result −

strcpy( str3, str1) : Hello


strcat( str1, str2): HelloWorld
strlen(str1) : 10

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 −

struct [structure tag] {

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;

Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member access operator is
coded as a period between the structure variable name and the structure member that we wish to access. You
would use the keyword struct to define variables of structure type. The following example shows how to use a
structure in a program −

Live Demo
#include <stdio.h>
#include <string.h>

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* 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;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

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

Structures as Function Arguments


You can pass a structure as a function argument in the same way as you pass any other variable or pointer.

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( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* 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;

/* print Book1 info */


printBook( Book1 );

/* Print Book2 info */


printBook( Book2 );

return 0;
}

void printBook( struct Books book ) {

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
54
printf( "Book book_id : %d\n", book.book_id);
}

When the above code is compiled and executed, it produces the following result −

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any other variable −

struct Books *struct_pointer;

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;

Let us re-write the above example using structure pointer.

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( ) {

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* 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;

/* print Book1 info by passing address of Book1 */


printBook( &Book1 );

/* print Book2 info by passing address of Book2 */


printBook( &Book2 );

return 0;
}

void printBook( struct Books *book ) {

printf( "Book title : %s\n", book->title);


printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}

When the above code is compiled and executed, it produces the following result −

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

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 −

union [union tag] {


member definition;
member definition;
...
member definition;
} [one or more union variables];

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or
any other valid variable definition. At the end of the union's definition, before the final semicolon, you can
specify one or more union variables but it is optional. 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( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}

When the above code is compiled and executed, it produces the following result −

Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator (.). The member access operator is
coded as a period between the union variable name and the union member that we wish to access. You would
use the keyword union to define variables of union type. The following example shows how to use unions in a
program −

Live Demo
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

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( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

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>

/* define simple structure */


struct {
unsigned int widthValidated;
unsigned int heightValidated;
} status1;

/* define a structure with bit fields */


struct {
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status2;

int main( ) {

printf( "Memory size occupied by status1 : %d\n", sizeof(status1));


printf( "Memory size occupied by status2 : %d\n", sizeof(status2));

return 0;
}

When the above code is compiled and executed, it produces the following result −

Memory size occupied by status1 : 8


Memory size occupied by status2 : 4

Bit Field Declaration


The declaration of a bit-field has the following form inside a structure −

struct {
type [member_name] : width ;
};

The following table describes the variable elements of a bit field −


60
Sr.No. Element & Description
type
1
An integer type that determines how a bit-field's value is interpreted. The type may be int, signed int, or
unsigned int.
member_name
2
The name of the bit-field.
width
3
The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified
type.

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 −

typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned char, for
example..

BYTE b1, b2;

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 −

typedef unsigned char byte;

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>

typedef struct Books {


char title[50];
char author[50];
char subject[100];
int book_id;
} Book;

int main( ) {

Book book;

strcpy( book.title, "C Programming");


strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);

return 0;
}

62
When the above code is compiled and executed, it produces the following result −

Book title : C Programming


Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407

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.

The following example shows how to use #define in a program −

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

C - Input and Output


When we say Input, it means to feed some data into a program. An input can be given in the form of a file or
from the command line. C programming provides a set of built-in functions to read the given input and feed it to
the program as per requirement.

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.

The Standard 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.

Standard File File Pointer Device


Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your 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 getchar() and putchar() Functions


The int getchar(void) function reads the next available character from the screen and returns it as an integer.
This function reads only single character at a time. You can use this method in the loop in case you want to read
more than one character from 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;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


putchar( 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 gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).

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];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

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 scanf() and printf() Functions


The int scanf(const char *format, ...) function reads the input from the standard input stream stdin and scans
that input according to the format provided.

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;

printf( "Enter a value :");


scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, 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 −

FILE *fopen( const char * filename, const char * mode );

Here, filename is a string literal, which you will use to name your file, and access mode can have one of the
following values −

Sr.No. Mode & Description


r
1
Opens an existing text file for reading purpose.
w
2
Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start
writing content from the beginning of the file.
a
3
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here
your program will start appending content in the existing file content.
r+
4
Opens a text file for both reading and writing.
w+
5
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists,
otherwise creates a file if it does not exist.
a+
6

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 −

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −

int fclose( FILE *fp );

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 −

int fputc( int c, FILE *fp );

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 −

int fputs( const char *s, FILE *fp );

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 −

int fgetc( FILE * fp );

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 −

char *fgets( char *buf, int n, FILE *fp );

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 );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );
fclose(fp);

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...

3: This is testing for fputs...

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 −

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);

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 −

Sr.No. Directive & Description


#define
1
Substitutes a preprocessor macro.
#include
2
Inserts a particular header from another file.
#undef
3
Undefines a preprocessor macro.
#ifdef
4
Returns true if this macro is defined.
#ifndef
5
Returns true if this macro is not defined.
#if
6
Tests if a compile time condition is true.
#else
7
The alternative for #if.
#elif
8

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

It tells the CPP to undefine existing FILE_SIZE and define it as 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.

Sr.No. Macro & Description


__DATE__
1
The current date as a character literal in "MMM DD YYYY" format.
__TIME__
2
The current time as a character literal in "HH:MM:SS" format.
__FILE__
3
This contains the current filename as a string literal.
__LINE__
4
This contains the current line number as a decimal constant.
__STDC__
5
Defined as 1 when the compiler complies with the ANSI standard.

Let's try the following example −

Live Demo
#include <stdio.h>

int main() {

printf("File :%s\n", __FILE__ );


printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );

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 −

The Macro Continuation (\) Operator

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 (#) Operator

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 −

Carole and Debra: We love you!

The Token Pasting (##) Operator

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>

#define tokenpaster(n) printf ("token" #n " = %d", token##n)

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 −

printf ("token34 = %d", token34);

72
This example shows the concatenation of token##n into token34 and here we have used both stringize and
token-pasting.

The Defined() Operator

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>

#if !defined (MESSAGE)


#define MESSAGE "You wish!"
#endif

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 −

Here is the message: You wish!

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;
}

We can rewrite above the code using a macro as follows −

#define square(x) ((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>

#define MAX(x,y) ((x) > (y) ? (x) : (y))

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 −

Max between 20 and 10 is 20

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 −

char *test (void);

74
and a main program called program.c that uses the header file, like this −

int x;
#include "header.h"

int main (void) {


puts (test ());
}

the compiler will see the same token stream as it would if program.c read.

int x;
char *test (void);

int main (void) {


puts (test ());
}

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

the entire header file 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() {

int sum = 17, count = 5;


double mean;

mean = (double) sum / count;


printf("Value of mean : %f\n", mean );
}

When the above code is compiled and executed, it produces the following result −

Value of mean : 3.400000

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 −

Value of sum : 116

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.

Usual Arithmetic Conversion


The usual arithmetic conversions are implicitly performed to cast their values to a common type. The
compiler first performs integer promotion; if the operands still have different types, then they are converted to
the type that appears highest in the following hierarchy −

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 −

Value of sum : 116.000000

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.

errno, perror(). and strerror()


The C programming language provides perror() and strerror() functions which can be used to display the text
message associated with errno.

 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>

extern int errno ;

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

Divide by Zero Errors


It is a common problem that at the time of dividing any number, programmers do not check if a divisor is zero
and finally it creates a runtime error.

The code below fixes this by checking if the divisor is zero before dividing −

Live Demo
#include <stdio.h>
#include <stdlib.h>

main() {

int dividend = 20;


int divisor = 0;
int quotient;

if( divisor == 0){


fprintf(stderr, "Division by zero! Exiting...\n");
exit(-1);
}

quotient = dividend / divisor;


fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(0);
}

When the above code is compiled and executed, it produces the following result −

Division by zero! Exiting...

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() {

int dividend = 20;


int divisor = 5;
int quotient;

if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}

quotient = dividend / divisor;


fprintf(stderr, "Value of quotient : %d\n", quotient );

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>

unsigned long long int factorial(unsigned int i) {

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 func(int, ... ) {


.
.
.
}

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>

double average(int num,...) {

va_list valist;
double sum = 0.0;
int i;

/* initialize valist for num number of arguments */


va_start(valist, num);

/* access all the arguments assigned to valist */


for (i = 0; i < num; i++) {
sum += va_arg(valist, int);
}

/* clean memory reserved for valist */


va_end(valist);

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.

Sr.No. Function & Description


void *calloc(int num, int size);
1
This function allocates an array of num elements each of which size in bytes will be size.
void free(void *address);
2
This function releases a block of memory block specified by address.
void *malloc(int num);
3
This function allocates an array of num bytes and leave them uninitialized.
void *realloc(void *address, int newsize);
4
This function re-allocates memory extending it upto newsize.

Allocating Memory Dynamically


While programming, if you are aware of the size of an array, then it is easy and you can define it as an array.
For example, to store a name of any person, it can go up to a maximum of 100 characters, so you can define
something as follows −

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;

strcpy(name, "Zara Ali");

/* allocate memory dynamically */


description = malloc( 200 * sizeof(char) );

if( description == NULL ) {


fprintf(stderr, "Error - unable to allocate required memory\n");
84
} else {
strcpy( description, "Zara ali a DPS student in class 10th");
}

printf("Name = %s\n", name );


printf("Description: %s\n", description );
}

When the above code is compiled and executed, it produces the following result.

Name = Zara Ali


Description: Zara ali a DPS student in class 10th

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.

Resizing and Releasing Memory


When your program comes out, operating system automatically release all the memory allocated by your
program but as a good practice when you are not in need of memory anymore then you should release that
memory by calling the function free().

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;

strcpy(name, "Zara Ali");

/* allocate memory dynamically */


description = malloc( 30 * sizeof(char) );

if( description == NULL ) {


fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcpy( description, "Zara ali a DPS student.");
}

/* suppose you want to store bigger description */


description = realloc( description, 100 * sizeof(char) );

if( description == NULL ) {

85
fprintf(stderr, "Error - unable to allocate required memory\n");
} else {
strcat( description, "She is in class 10th");
}

printf("Name = %s\n", name );


printf("Description: %s\n", description );

/* release memory using free() function */


free(description);
}

When the above code is compiled and executed, it produces the following result.

Name = Zara Ali


Description: Zara ali a DPS student.She is in class 10th

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.

C - Command Line Arguments


Advertisements

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>

int main( int argc, char *argv[] ) {

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.

$./a.out testing1 testing2


Too many arguments supplied.

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>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

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.

$./a.out "testing1 testing2"

Progranm name ./a.out


The argument supplied is testing1 testing2

87
C Programming Interview Questions

What is a pointer on pointer?

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.

Eg: int x = 5, *p=&x, **q=&p;

Therefore ‘x’ can be accessed by **q.

Distinguish between malloc() & calloc() memory allocation.

Both allocates memory from heap area/dynamic memory. By default calloc fills the allocated memory with 0’s.

What is keyword auto for?

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;
}

NOTE − A global variable can’t be an automatic variable.

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.

Explain the syntax for for loop.


for(expression-1;expression-2;expression-3) {
//set of statements
}

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.

How a negative integer is stored.

Get the two’s compliment of the same positive integer. Eg: 1011 (-5)

Step-1 − One’s compliment of 5 : 1010

Step-2 − Add 1 to above, giving 1011, which is -5

What is a static variable?

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.

What is a NULL pointer?

A pointer pointing to nothing is called so. Eg: char *p=NULL;

What is the purpose of extern storage specifier?

Used to resolve the scope of global symbol.

Eg:
main() {
extern int i;
Printf(“%d”,i);
}

int i = 20;
Explain the purpose of the function sprintf().

Prints the formatted output onto the character array.

What is the meaning of base address of the array?

The starting address of the array is called as the base address of the array.

When should we use the register storage specifier?

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?

S++, as it is single machine instruction (INC) internally.

What is a dangling pointer?

A pointer initially holding valid address, but later the held address is released or freed. Then such a pointer is
called as dangling pointer.

What is the purpose of the keyword typedef?

It is used to alias the existing type. Also used to simplify the complex declaration of the type.

What is lvalue and rvalue?

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.

What is the difference between actual and formal parameters?

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.

Can a program be compiled without main() function?

Yes, it can be but cannot be executed, as the execution requires main() function definition.

What is the advantage of declaring void pointers?

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.

Where an automatic variable is stored?

Every local variable by default being an auto variable is stored in stack memory.

What is a nested structure?

A structure containing an element of another structure as its member is referred so.

What is the difference between variable declaration and variable definition?

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.

Does a built-in header file contains built-in function definition?

No, the header file only declares function. The definition is in library which is linked by the linker.

Explain modular programming.

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.

Explain the use of %i format specifier w.r.t scanf().

Can be used to input integer in all the supported format.

How can you print a \ (backslash) using any of the printf() family of functions.

Escape it using \ (backslash).

Does a break is required by default case in switch statement?

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.

When to user -> (arrow) operator.

If the structure/union variable is a pointer variable, to access structure/union elements the arrow operator is
used.

What are bit fields?

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.

What are command line arguments?

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.

main( int count, char *args[]) {


}
What are the different ways of passing parameters to the functions? Which to use when?

 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.

What is the purpose of built-in stricmp() function.

It compares two strings by ignoring the case.

Describe the file opening mode “w+”.

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.

Where the address of operator (&) cannot be used?

It cannot be used on constants.

It cannot be used on variable which are declared using register storage class.

Is FILE a built-in data type?

No, it is a structure defined in stdio.h.

What is reminder for 5.0 % 2?

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?

There is only one operator and is conditional operator (? : ).

Which key word is used to perform unconditional branching?

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 (,).

Comma operator can be used to separate two or more expressions.

Eg: printf(“hi”) , printf(“Hello”);


What is a NULL statement?

A null statement is no executable statements such as ; (semicolon).

Eg: int count = 0;


while( ++count<=10 ) ;

Above does nothing 10 times.

What is a static function?

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?

Opiton –lm to be used as > gcc –lm <file.c>

Which operator is used to continue the definition of macro in the next line?

Backward slash (\) is used.

E.g. #define MESSAGE "Hi, \

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

void f(int k,…) {


}
What is the problem with the following coding snippet?
char *s1 = "hello",*s2 = "welcome";

strcat(s1,s2);

s1 points to a string constant and cannot be altered.

Which built-in library function can be used to re-size the allocated dynamic memory?
93
realloc().

Define an array.

Array is collection of similar data items under a common name.

What are enumerations?

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?

A variable is the name storage.

Who designed C programming language?

Dennis M Ritchie.

C is successor of which programming language?

What is the full form of ANSI?

American National Standards Institute.

Which operator can be used to determine the size of a data type or variable?

sizeof

Can we assign a float variable to a long integer variable?

Yes, with loss of fractional part.

Is 068 a valid octal number?

No, it contains invalid octal digits.

What it the return value of a relational operator if it returns any?

Return a value 1 if the relation between the expressions is true, else 0.

How does bitwise operator XOR works.

94
If both the corresponding bits are same it gives 0 else 1.

What is an infinite loop?

A loop executing repeatedly as the loop-expression always evaluates to true such as

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.

Can a pointer access the array?

Pointer by holding array’s base address can access the array.

What are valid operations on pointers?

The only two permitted operations on pointers are

 Comparision ii) Addition/Substraction (excluding void pointers)

What is a string length?

It is the count of character excluding the ‘\0’ character.

What is the built-in function to append one string to another?

strcat() form the header string.h

Which operator can be used to access union elements if union variable is a pointer variable?

Arrow (->) operator.

Explain about ‘stdin’.

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().

What is the purpose of #undef preprocessor?

It be used to undefine an existing macro definition.

Define a structure.

A structure can be defined of collection of heterogeneous data items.

Name the predefined macro which be used to determine whether your compiler is ANSI standard or not?

__STDC__

What is typecasting?

Typecasting is a way to convert a variable/constant from one type to another type.

What is recursion?

Function calling itself is called as recursion.

Which function can be used to release the dynamic allocated memory?

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?

On failure fopen() returns NULL, otherwise opened successfully.

What is the output file generated by the linker.

Linker generates the executable file.

What is the maximum length of an identifier?

Ideally it is 32 characters and also implementation dependent.

What is the default function call method?

By default the functions are called by value.

96
Functions must and should be declared. Comment on this.

Function declaration is optional if the same is invoked after its definition.

When the macros gets expanded?

At the time of preprocessing.

Can a function return multiple values to the caller using return reserved word?

No, only one value can be returned to the caller.

What is a constant pointer?

A pointer which is not allowed to be altered to hold another address after it is holding one.

To make pointer generic for which date type it need to be declared?

Void

Can the structure variable be initialized as soon as it is declared?

Yes, w.r.t the order of structure elements only.

Is there a way to compare two structure variables?

There is no such. We need to compare element by element of the structure variables.

Which built-in library function can be used to match a patter from the string?

Strstr()

What is difference between far and near pointers?

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.

Can we nest comments in a C code?

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.

Can the main() function left empty?

Yes, possibly the program doing nothing.

Can one function call another?

Yes, any user defined function can call any function.

Apart from Dennis Ritchie who the other person who contributed in design of C language.

Brain Kernighan

1) What is the difference between #include <file> and #include "file" ?

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.

2) Can #include handle other file formats than .h?

Yes. Irrespective of the file type, Preprocessor will do its job and will include any file like test.z.

3) What is a void pointer?

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.

Void PointerVoid(int type, void *a, void *b, void *c)

if(type == 1)/* int*/

98
*c = ((int) *a) + ((int)*b);

else /*string*/

sprintf((char*)c,”%s%s”,(char*)a,(char*b));

4) What is the value of NULL?

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.

5) Can the size of an array be declared at runtime?

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.

6) what is the difference between malloc() and calloc()?

Calloc Malloc

Allocates a region of memory large enough to hold


Allocates "size" bytes of memory.
"n” elements of "size" bytes each.

Malloc does not change the existing memory. So it returns


Calloc initializes the whole memory with 0
a memory chunk with garbage value.

7) What is the heap in memory?

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.

8) What will be the output of the following code snippet?

float num1 = 6 / 4;

float num2 = 6 / 4.0;

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.

9) What happens if you free a pointer twice?

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 */

12) How to print an address?

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.

13) Enter the output of the program

#include <stdio.h>

enum day {sunday = 1,monday,tuesday,wednesday,thursday = 3,friday,saturday};

int main()

int i;

printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,

wednesday, thursday, friday, saturday);

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.

15) What are the standard predefined macros?

ANSI C has six predefined macro. They are

 __FILE__ - Name of the current file


 __LINE__ - Current line number
 __TIME__ - Current time of compilation
 __DATE__ - Current date of compilation
 __cplusplus - If program compiled in C++ compiler
 __STDC__ - If ANSI C is followed by the compiler strictly.

16) What is a pragma?

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)

17) How to redefined macro with different value?


The #undef preprocessor can be used to reset a macro. For example,
#ifdef SAMPLE /* Checking if SAMPLE is defined */

#undef SAMPLE /* If so, then reset it */

#endif

#define SAMPLE 0 /* Then redefine with intended value */

18) What is an lvalue?

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.

19) How to assign one array to another?

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.

int x[5], y[5];

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.

21) What is the difference between ++X and X++?

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.

22) What happens when we use incremental operator in a pointer?

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

char p; p++; /* here p increments by 1*/

int p; p++;/* here p increments by 4(for 32 bit system)*/

23) What will be output of the following code snippet?

int num1=5;

int num2=5;

num1 =num1++ + num1--;

num2 =++num2 + --num2;

printf("num1=%d num2=%d",num1,num2);

Output will be num1=10 num2=10.


103
24) Can the sizeof operator be used to tell the size of an array passed to a function?

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.

25) Can you change the value of an array tag?

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.

26) What is a stream? How many types of streams are in C?

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.

Name Description Example

stdin Standard Input Keyboard

stdout Standard Output Screen

stderr Standard Error Screen

stdaux Standard Auxiliary COM1: port

stdprn Standard Printer LPT1: port

27) What are text and binary modes?

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.

28) Which one to use, a stream function or a system calls?

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.

30) How can I pad a string to a known length?

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.

31) How can I convert a number to a string?

The following functions can be used to convert integers to strings:

Function Name Purpose

itoa() Integer value to a string.

ltoa() Long integer value to a string.

Ultoa() Unsigned long integer value to a string.

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.

32) What does const keyword do?

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.

34) When should a type cast be used?

There are two main uses of type cast.

 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:

extern int decl1; /* this is a declaration */

int def2; /* this is a definition */

36) Can static variables be declared in a header file?

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.

38) What is a static function?

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.

40) How can you pass an array to a function by value?

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,

void func(int i[]) {..} /* parameter */

...

int k[10];

func(k); /* caller function */

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);

int main(int argc, char** argv)

...

atexit(_some_FUNC_);

….

107
}

42) What does a function declared as PASCAL do differently?

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:

int PASCAL pascal_func(int, char*, long);

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.

44) Is using exit() the same as using return?

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;

a>= 5 ? b=100 : b=200;

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);

46) Point out the error in the following program

main()

const int x;

x = 128;

printf("%d",x);

Variable x should have been initialized during declaration

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);

50) What is dangling pointer in c?

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

51) What is wild pointer in c?

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;

Output: Any address, Garbage value.

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.

52) What is the meaning of prototype of a function?

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,

int printf(const char *, int/);

53) Write a c program to find size of structure without using sizeof operator?

struct XXX

int x;

float y;

char z;

};

int main()

struct XXX *ptr=(struct XXX *)0;

ptr++;

printf("Size of structure is: %d",*ptr);

return 0;

54) What is size of void pointer?

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.

55) What will be output of following program?


112
#include<stdio.h>

int main()

int a = 260;

char *ptr;

ptr =( char *)&a;

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.

56) What will be the output?

#include "stdio.h"

int main()

char arr[100];

printf("%d", scanf("%s", arr));

/* Say the input is “hello” */

return 1;

113
The scanf returns the number of inputs it has successfully read, so the output will be 1.

57) Guess the output.

#include <stdio.h>

int main()

printf(6 + “Hello World”);

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”.

59) Guess the output?

#include <stdio.h>

int main()

printf("%c ", 6[“Hello World”]);

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'.

60) Guess the output?

#include <stdio.h>

main()
114
{

char *p = 0;

*p = 'a';

printf("value in pointer p is %c\n", *p);

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.

61) Which of the following is true

(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)

62) What is the output of this C Program?

#include<stdio.h>

int main()

printf("%d", printf("%d", 1234));

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.

63) How do you use a pointer to a function?


115
The hardest part about using a pointer-to-function is declaring it. Consider an example. You want to
create a pointer, pf, that points to the strcmp() function. The strcmp() function is declared as shown
below

int strcmp( const char *, const char * )

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:

int (*pf)( const char *, const char * );

Notice that you need to put parentheses around *pf.

64) When would you use a pointer to a function?

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 ?

Compilers for PC compatibles, use two types of pointers.

 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.

67) When should a far pointer be used?

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.

68) Expand the following fragment of C code to make it more understandable ?

{char* x = *y ? *++*y : *++*z;}

Code can be rewritten as

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

//59 is ASCII value of semicolon

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' ?

<...Add your code...>

if(a>10) printf("greater");

else if(a<10) printf("lesser");

118
else if(a==10) printf("equal");

else printf("unknown");

#define a b++

main()

int b = 10;

if(a>10) printf("greater");

else if(a<10) printf("lesser");

else if(a==10) printf("equal");

else printf("unknown");

Explanation: After macro expansion the code will be like this :

if(b++>5) printf("greater"); //5>5 : fail

else if(b++<5) printf("lesser"); //6

72) Can math operations be performed on a void pointer?

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.

73) How many parameters should a function have?

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.

74) Is using exit() the same as using return?

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.

75) Is it valid to address one element beyond the end of an array?

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

& i == & a[ MAX ]

is true or

& a[ MAX ] == & j

is true. This isn't guaranteed.

EMBEDDED C

1) What is the use of volatile keyword?

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.

2) Can a variable be both const and volatile?

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.

3) Can a pointer be volatile?

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.

4) What is size of character, integer, integer pointer, character pointer?

 The sizeof character is 1 byte.


 Size of integer is 4 bytes.
 Size of integer pointer and character is 8 bytes on 64 bit machine and 4 bytes on 32 bit machine.

5) What is NULL pointer and what is its use?

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.

6) What is void pointer and what is its use?

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.

8) What is return type of ISR?

ISR does not return anything. An ISR returns nothing because there is no caller in the code to read
the returned values.

9) What is interrupt latency?

Interrupt latency is the time required for an ISR responds to an interrupt.

10) How to reduce interrupt latency?

121
Interrupt latency can be minimized by writing short ISR routine and by not delaying interrupts for more
time.

11) Can we use any function inside ISR?

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.

13) Can we put breakpoint inside ISR?

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.

14) Can static variables be declared in a header file?

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.

15) Is Count Down_to_Zero Loop better than Count_Up_Loops?

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.

16) What are inline functions?

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.

17) Can include files be nested?

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.

18) What are the uses of the keyword static?

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.

19) What are the uses of the keyword volatile?

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.

20) What is Top half & bottom half of a kernel?

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.

21) Difference between RISC and CISC processor.

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.

22) What is RTOS?


In an operating system, there is a module called the scheduler, which schedules different tasks and
determines when a process will execute on the processor. This way, the multi-tasking is achieved.
The scheduler in a Real Time Operating System (RTOS) is designed to provide a predictable
execution pattern. In an embedded system, a certain event must be entertained in strictly defined
time.

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

 Context switching latency should be short.


 Interrupt latency should be short.
 Interrupt dispatch latency should be short.
 Reliable and time bound inter process mechanisms.
 Should support kernel preemption.

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.

24) What type of scheduling is there in RTOS?

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.

25) What is priority inversion?

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.

26) What is priority inheritance?

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.

27) How many types of IPC mechanism you know?

Different types of IPC mechanism are -

 Pipes
 Named pipes or FIFO
 Semaphores
 Shared memory
 Message queue
124
 Socket

28) What is semaphore?

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.

29) What is spin lock?

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.

30) What is difference between binary semaphore and mutex?

The differences between binary semaphore and mutex are as follows -

 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.

31) What is virtual memory?

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.

32) What is kernel paging?


125
Paging is a memory management scheme by which computers can store and retrieve data from the
secondary memory storage when needed in to primary memory. In this scheme, the operating system
retrieves data from secondary storage in same-size blocks called pages. The paging scheme allows
the physical address space of a process to be non continuous. Paging allows OS to use secondary
storage for data that does not fit entirely into physical memory.

33) Can structures be passed to the functions by value?

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.

34) Why cannot arrays be passed by values to functions?

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.

35) Advantages and disadvantages of using macro and inline functions?

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.

36) What happens when recursive functions are declared inline?

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.

38) ++*ip increments what?

It increments the value to which ip points to and not the address.

39) Declare a manifest constant that returns the number of seconds in a year using
preprocessor? Disregard leap years in your answer.

The correct answer will be -

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.

The correct answer is as follows -

 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.

42) What will be the output of the following code fragment?

127
char *ptr;

if ((ptr = (char *)malloc(0)) == NULL)

puts("Got a null pointer");

else

puts("Got a valid pointer");

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.

43) What is purpose of keyword const?

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 -

const int a; or int const a;

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;

44) What do the following declarations mean?

const int a;

int const a;

const int *a;


128
int * const a;

int const * a const;

 The first two means that a is a constant integer.


 The third declaration means that a is a pointer to a constant integer.
 The fourth means that a is a constant pointer to a non-constant integer.
 The fifth means that a is a constant pointer to a constant integer.

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;

unsigned char c[2];

};

union Test a = {300};

if((a.c [0] == 1) && (a.c [1] == 44))

printf ("BIG ENDIAN\n");

else

printf ("LITTLE ENDIAN\n");

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()

int var = 15;

printf(“%d”, SOME_MACRO(v, ar));

Output of the above program will be 15.

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.

48) Guess the output:

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.

49) What is forward reference w.r.t. pointers in c?

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;

Assuming that the generic list may be like this

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?

Bit field members can be declared as shown below


struct A

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 )

byte = byte >> field;

byte = byte & 0x01;

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.

54) What is job of preprocessor, compiler, assembler and linker ?

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.

56) What is the purpose of the preprocessor directive #error?

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

#error Include DEBUG or RELEASE in the makefile


133
#endif

#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.

This can be achieved by the following code fragment:

int *ptr;

ptr = (int *)0x67a9;

*ptr = 0xaa55;

58) Significance of watchdog timer in Embedded Systems.

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.

59) Why ++n executes faster than n+1?

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.

60) What is wild pointer?

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.

61) What is dangling pointer?

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

bit = (byte >> 4) & 0x01;

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.

64) When should we use register modifier?

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.

65) Why doesn't the following statement work?

char str[ ] = "Hello" ;

strcat ( str, '!' ) ;

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:

strcat ( str, "!" ) ;

66) Predict the output or error(s) for the following program:

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.

67)Guess the output:

#include<stdio.h>

main()

unsigned int a = 2;

int b = -10;

(a + b > 0)?puts("greater than 0"):puts("less than 1");

Output - greater than 0

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.

#define BIT(n) (0x1 << n)

int a;

void SetBit3()

a |= BIT(3);

}
136
void ClearBit3()

a &= ~BIT(3);

69) What is wrong with this code?

int square(volatile int *p)

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 square(volatile int *p)

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

1) What will be the output of printf(“%d”)?

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).

2) What is the return values of printf and scanf?

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.

3) How to free a block of memory previously allocated without using free?

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.

4) How can you print a string containing '%' in printf?

There are no escape sequence provided for '%' in C. To print '%' one should use '%%', like -

printf(“He got 90%% marks in math”);

5) What is use of %n in printf()?

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("Hello%n world ",&c);

printf("%d", c);

Above program will print 'Hello world 5 “ as Hello is 5 letter.

6) Swap two variables without using any control statement ?

We can swap variable using 2 methods. First method is as given below

#include <stdio.h>

main()

int a = 6;

int b = 10;

a = a + b;

b = a - b;

a = a - b;

printf("a: %d, b: %d\n", a, b);

Second method to swap variables is given below

#include <stdio.h>

main()

139
int a = 6;

int b = 10;

a ^= b;

b ^= a;

a ^= b;

printf("a: %d, b: %d\n", 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

But in case of second structure -

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.

8) How to call a function before main()?

To call a function pragma startup directive should be used. Pragma startup can be used like this -

#pragma startup fun

void fun()

printf(“In fun\n”);

main()

printf(“In main\n”);

The output of the above program will be -

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

9) What is rvalue and lvalue?

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.

10)How to pack a structure?

We can pack any structure using __attribute__((__packed__)) in gcc. Example -

typdef struct A __attribute __((__packed__))

char c;

int i;

}B;

We can also use, pragma pack like this -

#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.

11) How to convert a string to integer value?

We can convert a string to integer in two ways. Method 1:

int i = atoi(str);

142
Method 2:

sscanf(str, “%d”, &i);

12) Print the output of the following switch case program?

#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.

14) Which is better #define or enum?

 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);

printf("second A: %d\n", A);

Above program will print -

first A: 10

second A: 10

15) Print the output of this pointer program?

#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

You might also like