C Language Overview
C Language Overview
History of C
C was originally designed for and implemented on the UNIX operating system. C is not tied to any
particular hardware or system, however, and it is easy to write programs that will run without
change on any machine that supports C.
C is a general-purpose programming language with features economy of expression, modern
flow control and data structures and a rich set of operators. C is not a ‘‘very high level’’ language,
nor a ‘‘big’’ one, and is not specialized to any particular area of application. But its absence of
restrictions and its generality make it more convenient and effective for many tasks than
supposedly more powerful languages.
But the computing world has undergone a revolution since the publication of The C
Programming Language in 1978. Big computers are much bigger, and personal computers have
capabilities that rival mainframes of a decade ago. During this time, C has changed too, although
only modestly, and it has spread far beyond its origins as the language of the UNIX operating
system.
C has widely been used for various reason. Below are some benefits of using C
Easy to learn
Structured language
5. Variables and expressions may have types, indicating the nature of the expected values.
e.g. you might declare that one variable is expected to hold a number, and that another is
expected to hold a piece of text.
In many languages (including C), your declarations of variables you plan to use and what types
you expect them to hold must be clear.
Types of data types
single characters
Declaration char a
E.g. char a;
a=’k’;
OR char a=’k’;
real (floating point) numbers - these are numbers that contain decimals
Declaration float c
E.g. float c;
c=1.05;
OR float c=1.05;
7. Control flow constructs determine the order statements are performed in.
A certain statement might be performed only if a condition is true. A sequence of several
statements might be repeated over and over, until some condition is met; this is called a loop.
8. An entire set of statements, declarations, and control flow constructs can be lumped
together into a function (also called routine, subroutine, or procedure) which another piece of
code can then call as a unit. When you call a function, you transfer control to it and wait for it
to do its job, after which it returns to you; it may also return a value as a result of what it has
done. You may also pass values to the function on which it will operate or which otherwise
direct its work. Placing code into functions not only avoids repetition if the same sequence of
actions must be performed at several places within a program, but it also makes programs
easy to understand, because you can see that some function is being called, and performing
some (presumably) well-defined subtask, without always concerning yourself with the details
of how that function does its job. (If you've ever done any knitting, you know that knitting
instructions are often written with little sub-instructions or patterns which describe a
sequence of stitches which is to be performed multiple times during the course of the main
piece. These sub-instructions are very much like function calls in programming.)
9. A set of functions, global variables, and other elements makes up a program.
A source code for a program may be distributed among one or more source files.
C Program Structure
Let’s look into Hello World example using C Programming Language.
Before we study basic building blocks of the C programming language, let us look a bare
minimum C program structure so that we can take it as a reference in upcoming chapters.
Let us look at a simple code that would print the words "Hello World":
1. #include <stdio.h>
2. int main()
3. {
4. /* my first program in C */
5. printf("Hello, World! \n");
6. return 0;
7. }
1. The first line of the program #include <stdio.h> is a preprocessor command which tells a C
compiler to include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
5. The next line return 0; terminates main()function and returns the value 0.
C Basic Syntax
Tokens in C
printf
(
"Hello, World! \n"
)
;
Semicolons ;
In C program, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
Comments
Comments are like helping text in your C program and they are ignored by the compiler.
They start with /* and terminates with the characters */ as shown below:
/* my first program in C */
You can not have comments with in comments and they do not occur within a string or
character literals.
Identifiers
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
The following list shows the reserved words in C. These reserved words may not be used as
constant or variable or any other identifier names.
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a
C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to
identify where one element in a statement, such as int, ends and the next element begins.
Therefore, in the following statement:
int age;
There must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement
No whitespace characters are necessary between fruit and =, or between = and apples,
although you are free to include some if you wish for readability purpose.
C Data Types
Data types refers 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.
The types in C can be classified as follows:
Derived types:
4
They include (a) Pointer types, (b) Array types, (c) Structure types, (d)
Union types and
(e) Function
The array types andtypes.
structure types are referred to collectively as the aggregate types. The type
of a function specifies the type of the function's return value. We will see basic types in the
following section where as other types will be covered in the upcoming chapters.
Integer Types
Following table gives you detail about standard integer types with its storage sizes and
value ranges:
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. Following 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 following result on Linux:
Floating-Point Types
Following table gives you detail about standard float-point types with storage sizes and
value ranges and their precision:
#include <stdio.h>
#include <float.h>
int main()
{
printf("Storage size for float : %d \n", sizeof(float)); printf("Minimum float
positive value: %E\n", FLT_MIN ); printf("Maximum float positive value: %E\n",
FLT_MAX ); printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and execute the above program it produces following result on Linux:
Pointers to void
3
A pointer of type void * represents the address of an object, but not its type. For example a
memory allocation function void *malloc( size_t size ); returns a pointer to void which can be
casted to any data type.
The void type may not be understood to you at this point, so let us proceed and we will
cover these concepts in upcoming chapters.
C Variables
A variables is a name given to a storage area that 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 previous chapter, there will
be following basic variable types:
Type Description
C programming language also allows to define various other type 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.
Variable Declaration in C
All variables must be declared before we use them in C program, although certain declarations
can be made implicitly by content. A declaration specifies a type, and contains a list of one or
more variables of that type as follows:
type variable_list;
Here, type must be a valid C data type including char, int, float, double, or any user
defined data type etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid variable declarations are shown here:
A variable declaration does not allocate any memory space for the variable but a variable
definition allocate required memory space for that variable. A variable declaration with an
initial value as shown below will become variable definition and required memory is
allocated for the variable.
int i = 100;
An extern declaration is not a definition and does not allocate storage. In effect, it claims that
a definition of the variable exists somewhere else in the program. A variable can be declared
multiple times in a program, but it must be defined only once. Following is the declaration of a
variable with extern keyword:
extern int i;
Variable Initialization in C
Variables are initialized (assigned an value) with an equal sign followed by a constant
expression. The general form of initialization is:
variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows:
#include <stdio.h>
int main ()
{
/* variable declaration: */
int a, b; int c; float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of c : 30
value of f : 23.333334
Character constants
Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple
variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C when they are proceeded by a back slash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here you have
a list of some of such escape sequence codes:
Escape Meaning
sequence
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits
Following is the example to show few escape sequence characters:
#include <stdio.h>
int main()
{
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces following result:
Hello World
String literals
String literals or constants are enclosed in double quotes "". A string contains characters
that are similar to character literals: plain characters, escape sequences, and universal
characters.
You can break a long lines into multiple lines using string literals and separating them using
whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
return 0;
}
When the above code is compiled and executed, it produces following result:
value of area : 50
You can use const prefix to declare constants with a specific type as follows:
#include <stdio.h>
int main()
{
const int LENGTH = 10; const int WIDTH =
5; const char NEWLINE = '\n'; int area;
return 0;
}
When the above code is compiled and executed, it produces following result:
value of area : 50
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
#include <stdio.h>
main()
{
int a = 21; int b = 10; int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program it produces following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational Operators
Following table shows all the relational operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:
The following example shows how relational operators are used in C programming language:
#include <stdio.h>
main()
{
int a = 21; int b = 10; int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program it produces following result:
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0 then:
main()
{
int a = 5; int b = 20; int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}
}
When you compile and execute the above program it produces following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows:
Assume if A = 60; and B = 13; Now 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 Bitwise operators supported by C language are listed in the following table. Assume
variable A holds 60 and variable B holds 13 then:
~ Binary Ones Complement Operator is (~A ) will give -60 which is 1100
unary and has the effect of 'flipping' 0011
bits.
Try following example to understand all the bitwise operators available in C programming
language:
#include <stdio.h>
main()
{
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Assignment Operators
#include <stdio.h>
main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
When you compile and execute the above program it produces following result:
sizeof(a), where a is
sizeof() Returns the size of an variable. integer, will return 4.
If Condition is true ?
?: Conditional Expression
Then value X :
Otherwise value Y
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get 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.
#include <stdio.h>
main()
{
int a = 20; int b = 10;
int c = 15; int d = 5; int
e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5 printf("Value of (a + b) * c /
d is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n" , e );
return 0;
}
When you compile and execute the above program it produces following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
Decision Making in C
Decision making structures require that the programmer specify one or more conditions to
be evaluated or tested by the program, along with a statement or statements
to be executed if the condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false.
Following is the general from of a typical decision making structure found in most of the
programming languages:
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value. C programming language provides
following types of decision making statements.
if statement
Syntax
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 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.
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value.
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
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 following result:
if...else statement
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
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 of code will be executed
otherwise else block of code will be executed.
C programming language assumes any non-zero and non-null values as true and if it is
either zero or null then it is assumed as false value.
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces following result:
When using if , else if , else statements there are few points to keep in mind. An if can have
zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
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 */
}
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces following result:
Nested if statements
It is always legal in C programming to nest if-else statements, which 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 statement.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces following result:
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 */
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break; case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\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 following result:
Well done
Your grade is B
Syntax
switch(ch1) {
case 'A':
printf("This A is part of outer switch" );
switch(ch2) {
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* case code */
}
break;
case 'B': /* case code */
}
Example
#include <stdio.h>
int main ()
{
/* 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;
}
When the above code is compiled and executed, it produces following result:
The ? : Operator
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.