C Data Type Note

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

C Programming Language

C is a general-purpose language which has been closely associated with the UNIX operating
system for which it was developed - since the system and most of the programs that run it are
written in C.

Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-7. BCPL and B are
"type less" languages whereas C provides a variety of data types.

In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a revolution in the computing world.

In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C",
was completed late 1988.

Variables & Constant


Constants: Constants are the terms that can't be changed during the execution of a program.
For example: 1, 2.5, "Programming is easy." etc. In C, constants can be classified as:

1. Integer Constants: Integer constants are the numeric constants (constant associated
with number) without any fractional part or exponential part. H ere are three types of
integer constants in C language: Decimal Constant (base 10), Octal Constant(base 8) and
Hexadecimal Constant(base 16) .
 Decimal digits: 0 1 2 3 4 5 6 7 8 9
 Octal digits: 0 1 2 3 4 5 6 7
 Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
2. Floating-Point Constants: Floating point constants are the numeric constants that have
either fractional form or exponent form.
For example: -2.0 , 0.0000234 , -0.22E-5
3. Character Constants: Character constants are the constant which use single quotation
around characters. For example: 'a', 'l', 'm', 'F' etc.
Escape Sequences
Sometimes, it is necessary to use newline(enter), tab, quotation mark etc. in the program which
either cannot be typed or has special meaning in C programming. In such cases, escape
sequence are used. For example: \n is used for newline. The backslash( \ ) causes "escape" from
the normal way the characters are interpreted by the compiler.

\b Backspace \r Return \\ Backslash \? Question mark


\f Form feed \t Horizontal tab \' Single quotation mark \0 Null character
\n Newline \v Vertical tab \" Double quotation mark
4. String Constants: String constants are the constants which are enclosed in a pair of
double-quote marks.
For example:
"good" //string constant
"" //null string constant
" " //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline

1
Variables: A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable.

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. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −

Type Description

char Typically a single octet (one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.


C programming language also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this
chapter, let us study only basic variable types.

-: Data Types in C :-
Data types specify how we enter
data into our programs and what
type of data we enter. C language
has some predefined set of data
types to handle various kinds of
data that we use in our program.
These data types have different
storage capacities.

C language supports 2 different


type of data types,

Primary data types


These are fundamental data types in
C namely integer(int), floating(float), charater(char) and void.

Derived data types


Derived data types are like arrays, functions, structures and pointers. These are discussed in
detail later.

Integer type
Integers are used to store whole numbers.

2
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

long int or signed long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

Floating type
Floating types are used to store real numbers.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Character type
Character types are used to store characters value.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

void type

void type means no value. This is usually used to specify the type of functions.
Note:
 Signed data types can hold both positive and negative values.
 Unsigned data types can hold large positive values but cannot hold negative values.
List of Format Specifiers In C Language ;-
In C programming we need lots of format specifier to work with various data types. Format specifiers
defines the type of data to be printed on standard output. Whether to print formatted output or to
take formatted input we need format specifiers. Format specifiers are also called as format string.
Here is a complete list of all format specifiers used in C programming language.

3
Format specifier Description Supported data types
char
%c Character
unsigned char
short
unsigned short
%d Signed Integer
int
long
float
%e or %E Scientific notation of float values
double
%f Floating point float
float
%g or %G Similar as %e or %E
double
%hi Signed Integer(Short) short
%hu Unsigned Integer(Short) unsigned short
short
unsigned short
%i Signed Integer
int
long
%l or %ld or %li Signed Integer long
%lf Floating point double
%Lf Floating point long double
unsigned int
%lu Unsigned integer
unsigned long
%lli, %lld Signed Integer long long
%llu Unsigned Integer unsigned long long
short
unsigned short
%o Octal representation of Integer. int
unsigned int
long
%p Address of pointer to void void * void *
%s String char *
unsigned int
%u Unsigned Integer
unsigned long
short
unsigned short
%x or %X Hexadecimal representation of Unsigned Integer int
unsigned int
long
%n Prints nothing
%% Prints % character

-: Operators in C :-
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.
C language is rich in built-in operators and provides the following types of operators −
 Arithmetic Operators  Bitwise Operators
 Relational Operators  Assignment Operators
 Logical Operators  Misc Operators

We will, in this chapter, look into the way each operator works.

4
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −

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
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −

Operator Description Example

Checks if the values of two operands are equal or not. If yes, then the (A == B) is not
==
condition becomes true. true.

Checks if the values of two operands are equal or not. If the values are (A != B) is true.
!=
not equal, then the condition becomes true.

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand. If yes, then the condition becomes true. true.

Checks if the value of left operand is less than the value of right (A < B) is true.
<
operand. If yes, then the condition becomes true.

Checks if the value of left operand is greater than or equal to the value (A >= B) is not
>=
of right operand. If yes, then the condition becomes true. true.

Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand. If yes, then the condition becomes true. true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then –

5
Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the (A && B) is
condition becomes true. false.

|| Called Logical OR Operator. If any of the two operands is non-zero, then (A || B) is


the condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the logical state of its !(A && B) is
operand. If a condition is true, then Logical NOT operator will make it true.
false.

Bitwise Operators
Bitwise operator works on bits and performs 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 both (A & B) = 12, i.e.,
&
operands. 0000 1100

Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e.,


|
0011 1101

Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49, i.e.,
^
not both. 0011 0001

Binary Ones Complement Operator is unary and has the effect of (~A ) = -61, i.e,.
~ 'flipping' bits. 1100 0011 in 2's
complement form.

6
Binary Left Shift Operator. The left operands value is moved left A << 2 = 240 i.e.,
<<
by the number of bits specified by the right operand. 1111 0000

Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e.,
>>
right by the number of bits specified by the right operand. 0000 1111

Assignment Operators
The following table lists the assignment operators supported by the C language −

Operator Description Example

Simple assignment operator. Assigns values from right side C = A + B will assign
=
operands to left side operand the value of A + B to C

Add AND assignment operator. It adds the right operand to the C += A is equivalent to
+=
left operand and assign the result to the left operand. C=C+A

Subtract AND assignment operator. It subtracts the right C -= A is equivalent to


-= operand from the left operand and assigns the result to the left C=C-A
operand.

Multiply AND assignment operator. It multiplies the right C *= A is equivalent to


*= operand with the left operand and assigns the result to the left C=C*A
operand.

Divide AND assignment operator. It divides the left operand C /= A is equivalent to


/= with the right operand and assigns the result to the left C=C/A
operand.

Modulus AND assignment operator. It takes modulus using two C %= A is equivalent to


%=
operands and assigns the result to the left operand. C=C%A

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.

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

?: Conditional Expression. If Condition is true ? then value X : otherwise value Y

Operators Precedence in C
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 + - ! ~ ++ - - (type)* & sizeof Right to left

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

8
Reserved Word in C:-
The following names are reserved by the C language. Their meaning is already defined, and they
cannot be re-defined to mean anything else.

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

do int struct _Packed

double

While naming your functions and variables, other than these names, you can choose any names
of reasonable length for variables, functions etc.

Library Functions in C:-


 Library functions in C language are inbuilt functions which are grouped together and placed
in a common place called library.
 Each library function in C performs specific operation.
 We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
 These library functions are created by the persons who designed and created C compilers.
 All C standard library functions are declared in many header files which are saved as
file_name.h.
 Actually, function declaration, definition for macros are given in all header files.
 We are including these header files in our C program using “#include<file_name.h>” command
to make use of the functions those are declared in the header files.
 When we include header files in our C program using “#include<filename.h>” command, all C
code of the header files are included in C program. Then, this C program is compiled by
compiler and executed.
 If you want to check source code for all header files, you can check inside “include” directory
after C compiler is installed in your machine.
 For example, if you install DevC++ compiler in C directory in your machine, “C:\Dev-Cpp\
include” is the path where all header files will be available.

List of most used header files in C:

 Check the below table to know all the C library functions and header files in which they are
declared.
 Click on the each header file name below to know the list of inbuilt functions declared inside
them.

S.No Header file Description


1 stdio.h This is standard input/output header file in which Input/Output functions are declared
2 conio.h This is console input/output header file
3 string.h All string related functions are defined in this header file
4 stdlib.h This header file contains general functions used in C programs
5 math.h All maths related functions are defined in this header file
6 time.h This header file contains time and clock related functions

9
7 ctype.h All character handling functions are defined in this header file
8 stdarg.h Variable argument functions are declared in this header file
9 signal.h Signal handling functions are declared in this file
10 setjmp.h This file contains all jump functions
11 locale.h This file contains locale functions
12 errno.h Error handling functions are given in this file
13 assert.h This contains diagnostics functions

C Provides Two Styles of Flow Control:

 Branching

 Looping

Branching is deciding what actions to take and looping is deciding how many times to
take a certain action.

Branching:

Branching is so called because the program chooses to follow one branch or another.

if statement

This is the simplest form of the branching statements.

It takes an expression in parenthesis and a statement or block of statements. if the


expression is true then the statement or block of statements gets executed otherwise
these statements are skipped.

NOTE: Expression will be assumed to be true if their evaluated value is non-zero.

if statements take the following form:

Basic syntax of while loop is as follows:

if (expression)
statement;
or
if (expression)
{
Block of statements;
}
or
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
or
if (expression)
{

10
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}
? : Operator

The? : Operator is just like an if ... else statement except that because it is an operator
you can use it within expressions.

? : is a ternary operator in that it takes three values, this is the only ternary operator C
has.

? : takes the following form:

Basic syntax of while loop is as follows:

if condition is true ? then X return value : otherwise Y value;

Switch Statement:

The switch statement is much like a nested if .. else statement. It’s mostly a matter of
preference which you use, switch statement can be slightly more efficient and easier to
read.

Basic syntax of while loop is as follows:

switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}

Using break keyword:

If a condition is met in switch case then execution continues on into the next case
clause also if it is not explicitly specified that the execution should exit the switch
statement. This is achieved by using break keyword.

What is default condition:

If none of the listed conditions is met then default condition executed.

Looping

11
Loops provide a way to repeat commands and control how many times they are repeated.
C provides a number of looping way.

while loop

The most basic loop in C is the while loop.A while statement is like a repeating if
statement. Like an If statement, if the test condition is true: the statements get executed.
The difference is that after the statements have been executed, the test condition is
checked again. If it is still true the statements get executed again. This cycle repeats
until the test condition evaluates to false.

Basic syntax of while loop is as follows:

while ( expression )
{
Single statement
or
Block of statements;
}

for loop

for loop is similar to a while, it's just written differently. for statements are often used to
process lists such a range of numbers:

Basic syntax of for loop is as follows:

for( expression1; expression2; expression3)


{
Single statement
or
Block of statements;
}

In the above syntax:

 expression1 - Initialisese variables.


 expression2 - Condtional expression, as long as this condition is true, loop will
keep executing.
 expression3 - expression3 is the modifier which may be simple increment of a
variable.

do...while loop

do ... while is just like a while loop except that the test condition is checked at the end
of the loop rather than the start. This has the effect that the content of the loop are
always executed at least once.

Basic syntax of do...while loop is as follows:

do
{
Single statement

12
or
Block of statements;
}while(expression);

break and continue statements

C provides two commands to control how we loop:

 break -- exit form loop or switch.


 continue -- skip 1 iteration of loop.

You already have seen example of using break statement. Here is an example showing
usage of continue statement.

#include
main()
{
int i;
int j = 10;

for( i = 0; i <= j; i ++ )
{
if( i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}
}

This will produce following output:

Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10

Input and Output Function in C:-


Input : In any programming language input means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a set of built-in
functions to read given input and feed it to the program as per requirement.
Output : In any programming language output means to display some data on screen, printer or
in any file. C programming language provides a set of built-in functions to output required data.
Here we will discuss only one input function and one output function just to understand the
meaning of input and output.
printf() function

13
This is one of the most frequently used functions in C for output.
Try following program to understand printf() function.
#include <stdio.h>

main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;

printf("%d %s %f %c\n", dec, str, pi, ch);


}
The output of the above would be:
5 abc 3.140000 c
Here %d is being used to print an integer, %s is being used to print a string, %f is being used to
print a float and %c is being used to print a character.
scanf() function
This is the function which can be used to to read an input from the command line.
Try following program to understand scanf() function.
#include <stdio.h>

main()
{
int x;
int args;

printf("Enter an integer: ");


if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}
Here %d is being used to read an integer value and we are passing &x to store the vale read
input. Here &indicates the address of variable x.
This program will prompt you to enter a value. Whatever value you will enter at command
prompt that will be output at the screen using printf() function. If you enter a non-integer value
then it will display an error message.
Enter an integer: 20
Read in 20

Array in C
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables 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.

14
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
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};
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. The following example Shows how to use all the three above mentioned concepts viz.
declaration, assignment, and accessing arrays −
#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 */

15
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
Element[9] = 109

Multi-Dimensional Array

C programming language allows multidimensional arrays. Here is the general form of a


multidimensional array declaration −

type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −

int threedim[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. 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 −

16
Thus, every element in the array a is identified by an element name of the forma[ 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
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];


The above statement will take the 4th element from the 3rd row of the array. You can verify it in
the above figure. Let us check the following program where we have used a nested loop to
handle a two-dimensional array −

#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

17
As explained above, you can have arrays with any number of dimensions, although it is likely
that most of the arrays you create will be of one or two dimensions.

Functions in C
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
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.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
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.
Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −
/* 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;
}

18
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 );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
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.
Calling a Function
While creating a C function, you give a definition of what the function has to do. 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 −
#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;

19
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
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 −
Call Type & Description

Call by value
This method 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.

Call by reference
This method 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. This
means that changes made to the parameter affect the argument.

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.

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. Consider the
function swap() definition as follows.

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

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

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.

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;

21
}
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
* &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.

22

You might also like