C Data Type Note
C Data Type Note
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.
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.
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
-: 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.
Integer type
Integers are used to store whole numbers.
2
Size and range of Integer type on 16-bit machine
Floating type
Floating types are used to store real numbers.
Character type
Character types are used to store characters value.
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 −
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −
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 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 −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12, i.e.,
&
operands. 0000 1100
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 −
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
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.
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.
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.
double
While naming your functions and variables, other than these names, you can choose any names
of reasonable length for variables, functions etc.
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.
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
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
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.
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.
switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}
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.
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.
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:
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.
do
{
Single statement
12
or
Block of statements;
}while(expression);
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 );
}
}
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
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;
main()
{
int x;
int args;
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 −
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 () {
15
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
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
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'.
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 −
#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) {
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 () {
return 0;
}
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.
int temp;
x = y; /* put y into x */
return;
20
Now, let us call the function swap() by passing actual values as in the following example −
#include <stdio.h>
/* function declaration */
int main () {
int a = 100;
int b = 200;
swap(a, b);
return 0;
Let us put the above code in a single C file, compile and execute it, it will produce the following
result −
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.
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 −
22