Basics of C Programming Overview
Basics of C Programming Overview
25ES105 - C Programing
UNIT - I
BASICS OF C PROGRAMMING
Imperative programming is divided into three broad categories: Procedural, OOP and parallel
processing. These paradigms are as follows:
It is a type of programming in which programmers define not only the data type of a data structure, but
also the types of operations (functions) that can be applied to the data structure.
In this way, the data structure becomes an object that includes both data and functions. In addition,
programmers can create relationships between one object and another. For example, objects can inherit
characteristics from other objects.
History of C Programming
C is a general purpose structured programming language.
C was developed by Dennis Ritchie at AT & T Bell laboratories in 1972. It is an outgrowth of an earlier
language called BCPL & B.
It was named as C to present it as the successor of B language which was developed earlier by Ken
Thompson in 1970 at AT & T Bell laboratories.
C is a highly portable, which means that C program written for one computer can be run on another with
little or no modification.
C is well suited for structured programming; thus user has to think of a problem in terms of function
modules and blocks.
The proper collection of these modules would make a complete program. This modular structure makes
program debugging, testing and maintenance easier.
C program is basically a collection of functions that are supported by the C library. We can add our
own functions to the C library. With the availability of a large number of functions, the programming
task becomes simple.
Features of C Programming
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
Applications of C Language
1. Operating Systems
The first operating system to be developed using a high-level programming language was UNIX, which
was designed in the C programming language. Later on, Microsoft Windows and various Android
applications were scripted in C.
2. Embedded Systems
The C programming language is considered an optimum choice when it comes to scripting applications
and drivers of embedded systems, as it is closely related to machine hardware.
3. GUI
GUI stands for Graphical User Interface. Adobe Photoshop, one of the most popularly used photo
editors since olden times, was created with the help of C.
Later on, Adobe Premiere and Illustrator were also created using C.
4. Google
Google file system and Google chromium browser were developed using C/C++. Not only this, the
Google Open Source community has a large number of projects being handled using C/C++.
5. Compiler Design
One of the most popular uses of the C language was the creation of compilers.
Several popular compilers were designed using C such as Bloodshed Dev-C, Clang C, MINGW, and
Apple C.
Since the C programming language is relatively faster than Java or Python, as it is compiler-based, it
finds several applications in the gaming sector.
Some of the simplest games are coded in C such as Tic-Tac-Toe, The Dino game, The Snake game etc.,
Structure of C Program
The user defined function section (or) the Sub program section contains user defined functions which
are called by the main function.
Each user defined function contains the function name, the argument and the return value.
Example:
In ‘C’ language each and every individual unit is called as Token or Lexical element.
i) Character set
ii) Delimiters
iii) Keywords
iv) Identifiers
v) Data types
vi) Constants
vii) Variables
Character Set
It is the basic building block to form program elements. The set of characters used in a language is
known as its character set.
The C character set consists of upper and lower case alphabets, digits, special characters and white
spaces.
The alphabets and digits are together called the alphanumeric characters.
Delimiters
In C programming, delimiters are special characters or symbols that serve to separate or define various
elements within the code, helping the compiler understand the structure and meaning of the
program. They mark the boundaries of different units, such as statements, blocks, expressions, and data
elements.
Keywords
Keywords in C are predefined, reserved words that hold special meaning to the C compiler and are used
to perform specific tasks within a program.
They are fundamental building blocks of the C language, and their meaning cannot be altered by the
programmer.
Keywords are predefined or reserved words that have special meanings to the compiler
Example:
#include <stdio.h
int main() {
int return = 10;
printf("%d\n", return);
return 0;
}
Output
./Solution.c: In function 'main':
./Solution.[Link] error: expected identifier or '(' before 'return'
int return = 10;
^
./Solution.[Link] error: expected expression before 'return'
printf("%d\n", return);
^
Let's categorize all keywords based on context for a more clear understanding.
Category Keywords
Data Type Keywords char, int, float, double, void, short, long, signed, unsigned
Operator & Utility Keywords sizeof, return, goto, typedef
Control Flow Keywords if, else, switch, case, default, for, while, do, break, continue
Storage Class Keywords auto, register, static, extern
Type Qualifiers const, volatile
User Defined Types struct, union, enum
Identifiers
In C programming, identifiers are the names used to identify variables, functions, arrays, structures, or
any other user-defined items.
It is a name that uniquely identifies a program element and can be used to refer to it later in the
program.
Example:
// Creating a variable
int val = 10;
// Creating a function
void func() {}
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.
A related concept is that of "variables", which refer to the addressable location in the memory of the
processor. The data captured via different input devices is stored in the computer memory. A symbolic name
can be assigned to the storage location called variable name.
The following table provides the details of standard floating-point types with storage sizes and value ranges and
their precision:
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
The header file "float.h" defines the macros that allow you to use these values and other details about the
binary representation of real numbers in your programs.
Note: "sizeof" returns "size_t". The type of unsigned integer of "size_t" can vary depending on platform. And, it
may not be long unsigned int everywhere. In such cases, we use "%zu" for the format string instead of
"%d".
User-defined Data Types in C
There are two user-defined data types struct and union, that can be defined by the user with the help of
the combination of other basic data types.
An array is a collection of multiple values of same data type stored in consecutive memory locations.
The size of array is mentioned in square brackets [].
For example,
int marks[5];
Arrays can be initialized at the time of declaration. The values to be assigned are put in parentheses.
C also supports multi-dimensional arrays.
int marks[ ]={50,56,76,67,43};
A pointer is a special variable that stores address or reference of another variable/object in the memory.
The name of pointer variable is prefixed by asterisk (*).
The type of the pointer variable and the variable/object to be pointed must be same.
int x;
int *y;
y = &x;
Here, "y" is a pointer variable that stores the address of variable "x" which is of "int" type.
Pointers are used for many different purposes.
Text string manipulation and dynamic memory allocation are some of the processes where the use of
pointers is mandatory.
Constants
In C programming, const is a keyword used to declare a variable as constant, meaning its value cannot
be changed after it is initialized.
It is mainly used to protect variables from being accidentally modified, making the program safer and
easier to understand.
These constants can be of various types, such as integer, floating-point, string, or character constants.
Example:
#include <stdio.h>
int main() {
// Defining constant variable
const int a = 10;
printf("%d", a);
return 0;
}
Output
10
Syntax
We define a constant in C using the const keyword. Also known as a const type qualifier, the const
keyword is placed at the start of the variable declaration to declare that variable as a constant.
const data_type var_name = value;
Variables
A variable in C is a named piece of memory which is used to store data and access it whenever
required. It allows us to use the memory without having to memorize the exact memory address.
To create a variable in C, we have to specify a name and the type of data it is going to store in the
syntax.
data_type name;
C provides different data types that can store almost all kinds of data. For example, int, char, float,
double, etc.
int num;
char letter;
float decimal;
In C, every variable must be declared before it is used. We can also declare multiple variables of same
data type in a single statement by separating them using comma as shown:
data_type name1, name2, name3, ...;
1
3
Assign Values Manually
We can also manually assign desired values to the enum names as shown:
enum enum_name {
n1 = val1, n2 = val2, n3, ...
};
It is not mandatory to assign all constants. The next name will be automatically assigned a value by
incrementing the previous name's value by 1. For example, n3 here will be (val2 + 1). Also, we can
assign values in any order, but they must be integer only.
Example:
#include <stdio.h>
// Defining enum
enum enm {
a = 3, b = 2, c };
int main() {
// Creating enum variable
enum enm v1 = a;
enum enm v2 = b;
enum enm v3 = c;
printf("%d %d %d", v1, v2, v3);
return 0; }
Output
323
In the above program, a is assigned the value 3, b is assigned 2, and c will automatically be assigned
the value 3, as the enum values increment from the last assigned value.
We can also confirm here that two enum names can have same value.
Operators
Operators are the basic components of C programming. They are symbols that represent some kind of
operation, such as mathematical, relational, bitwise, conditional, or logical computations, which are to
be performed on values or variables.
The values and variables used with operators are called operands.
Example:
#include <stdio.h>
int main() {
// Expression for getting sum
int sum = 10 + 20;
printf("%d", sum);
return 0;
}
Output
30
int main() {
int a = 25, b = 5;
// using operators and printing results
printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
printf("a-- = %d\n", a--);
return 0;
}
Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26
Relational Operators
The relational operators in C are used for the comparison of the two operands.
Example:
#include <stdio.h>
int main() {
int a = 25, b = 5;
// using operators and printing results
printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);
return 0;
}
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
Example:
#include <stdio.h>
int main() {
int a = 25, b = 5;
// using operators and printing results
printf("a && b : %d\n", a && b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);
return 0;
}
Output
a && b : 1
a || b : 1
!a: 0
Bitwise Operators
The Bitwise operators are used to perform bit-level operations on the operands.
The operators are first converted to bit-level and then the calculation is performed on the operands.
Note: Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.
Example:
int main() {
int a = 25, b = 5;
// using operators and printing results
printf("a & b: %d\n", a & b);
printf("a | b: %d\n", a | b);
printf("a ^ b: %d\n", a ^ b);
printf("~a: %d\n", ~a);
printf("a >> b: %d\n", a >> b);
printf("a << b: %d\n", a << b);
return 0; }
Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
a >> b: 0
a << b: 800
Assignment Operators
Assignment operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the compiler will
raise an error.
The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.
Symbol Operator Description Syntax
= Simple Assign the value of the right operand to the left a = b
Assignment operand.
+= Plus and assign Add the right operand and left operand and assign a += b
this value to the left operand.
-= Minus and assign Subtract the right operand and left operand and a -= b
assign this value to the left operand.
*= Multiply and Multiply the right operand and left operand and a *= b
assign assign this value to the left operand.
/= Divide and assign Divide the left operand with the right operand and a /= b
assign this value to the left operand.
%= Modulus and Assign the remainder in the division of left operand a %= b
assign with the right operand to the left operand.
&= AND and assign Performs bitwise AND and assigns this value to the a &= b
left operand.
|= OR and assign Performs bitwise OR and assigns this value to the a |= b
left operand.
^= XOR and assign Performs bitwise XOR and assigns this value to the a ^= b
left operand.
>>= Rightshift and Performs bitwise Rightshift and assign this value to a >>= b
assign the left operand.
<<= Leftshift and Performs bitwise Leftshift and assign this value to a <<= b
assign the left operand.
Example:
int main() {
int a = 25, b = 5;
// using operators and printing results
printf("a = b: %d\n", a = b);
printf("a += b: %d\n", a += b);
printf("a -= b: %d\n", a -= b);
printf("a *= b: %d\n", a *= b);
printf("a /= b: %d\n", a /= b);
printf("a %%= b: %d\n", a %= b);
printf("a &= b: %d\n", a &= b);
printf("a |= b: %d\n", a |= b);
printf("a ^= b: %d\n", a ^= b);
printf("a >>= b: %d\n", a >>= b);
printf("a <<= b: %d\n", a <<= b);
return 0;
}
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a ^= b: 0
a >>= b: 0
a <<= b: 0
sizeof Operator
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)
Comma Operator ( , )
The comma operator (represented by the token) is a binary operator that evaluates its first operand
and discards the result, it then evaluates the second operand and returns this value (and type).
The comma operator has the lowest precedence of any C operator. It can act as both operator and
separator.
Syntax
operand1 , operand2
Conditional Operator ( ? : )
The conditional operator is the only ternary operator in C++. It is a conditional operator that we can
use in place of if..else statements.
Syntax
expression1 ? Expression2 : Expression3;
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we
will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
dot (.) and arrow (->) Operators
Member operators are used to reference individual members of classes, structures, and unions.
The dot operator is applied to the actual object.
The arrow operator is used with a pointer to an object.
Syntax
structure_variable . member;
structure_pointer -> member;
addressof (&) and Dereference (*) Operators
Addressof operator & returns the address of a variable and the dereference operator * is a pointer
to a variable. For example *var; will pointer to a variable var.
Precedence and Associativity
Operator precedence and associativity are rules that decide the order in which parts of an expression
are calculated.
Precedence tells us which operators should be evaluated first, while associativity determines the
direction (left to right or right to left) in which operators with the same precedence are evaluated.
Example:
#include <stdio.h>
int main() {
int a = 6, b = 3, c = 4;
int res;
// Precedence and associativity applied here
res = a + b * c / 2;
printf("%d", res);
return 0;
}
Output
12
Operator Associativity
Operator associativity is used when two operators of the same precedence appear in an expression.
Associativity can be either from Left to Right or Right to Left. Let's evaluate the following
expression,
100 / 5 % 2
The division (/) and modulus (%) operators have the same precedence, so the order in which they are
evaluated depends on their left-to-right associativity.
This means the division is performed first, followed by the modulus operation. After the calculations,
the result of the modulus operation is determined.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the associativity for each of
the operators:
Precedence Operator Description Associativity
Higher to Lower
1 () Parentheses (function call) Left-to-Right
[] Array Subscript (Square Brackets)
. Dot Operator
-> Structure Pointer Operator
++ , -- Postfix increment, decrement
2 ++ / -- Prefix increment, decrement Right-to-Left
+/- Unary plus, minus
!,~ Logical NOT, Bitwise complement
(type) Cast Operator
* Dereference Operator
& Addressof Operator
sizeof Determine size in bytes
3 *,/,% Multiplication, division, modulus Left-to-Right
4 +/- Addition, subtraction Left-to-Right
5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right
6 < , <= Relational less than, less than or equal to Left-to-Right
> , >= Relational greater than, greater than or equal to
7 == , != Relational is equal to, is not equal to Left-to-Right
8 & Bitwise AND Left-to-Right
9 ^ Bitwise exclusive OR Left-to-Right
10 | Bitwise inclusive OR Left-to-Right
11 && Logical AND Left-to-Right
12 || Logical OR Left-to-Right
13 ?: Ternary conditional Right-to-Left
14 = Assignment Right-to-Left
+= , -= Addition, subtraction assignment
*= , /= Multiplication, division assignment
%= , &= Modulus, bitwise AND assignment
^= , |= Bitwise exclusive, inclusive OR assignment
<<=, >>= Bitwise shift left, right assignment
15 , comma (expression separator) Left-to-Right
Bit manipulations
In C, bitwise operators are used to perform operations directly on the binary representations of
numbers. These operators work by manipulating individual bits (0s and 1s) in a number.
Let’s look at the truth table of the bitwise operators.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
a&b = 1
a|b = 13
a^b = 12
~a = 4294967290
b<<1 = 18
b>>1 = 4
Expressions
Types of Expression
Output
Enter a character:
a (Entered by the user)
Entered character is: a
Reading a string
The scanf() function can also be used to read string input from users. But it can only read single words.
#include <stdio.h>
int main() {
char str[100]; // Declare an array to hold the input string
printf("Enter a string: ");
scanf("%s", str); // Reads input until the first space or newline
printf("You entered: %s\n", str);
return 0; }
Output:
Enter a String:
Geeks (Entered by the user)
Entered string is: Geeks
The scanf() function can not handle spaces and stops at the first blanksspace. to handle this situation
we can use fgets() which is a better alternative as it can handle spaces and prevent buffer overflow.
fgets()
fgets() reads the given number of characters of a line from the input and stores it into the specified
string. It can read multiple words at a time.
Syntax
fgets(str, n, stdin);
where buff is the string where the input will be stored and n is the maximum number of characters to
read. stdin represents input reading from the keyboard.
Example:
#include <stdio.h>
#include <string.h>
int main() {
// String variable
char name[20];
printf("Enter your name: \n");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
Output
Enter your name:
John (Entered by User)
Hello, John
The printf() function is used to print formatted output to the standard output stdout (which is
generally the console screen). It is one of the most commonly used functions in C.
Syntax
printf("formatted_string", variables/values);
Where,
Formatted String: string defining the structure of the output and include format specifiers
variables/values: arguments passed to printf() that will replace the format specifiers in the formatted
string.
Examples
The following examples demonstrate the use of printf for output in different cases:
Printing Some Text
Example:
int main() {
// Prints some text
printf("First Print");
return 0; }
Output
First Print
Explanation: The text inside "" is called a string in C. It is used to represent textual information. We can
directly pass strings to the printf() function to print them in console screen.
fputs()
The fputs() function is used to output strings to the files but we can also use it to print strings to the console
screen.
Syntax:
fputs("your text here", stdout); // Where, the stdout represents that the text should be printed to console.
Example:
#include <stdio.h>
int main() {
fputs("This is my string", stdout);
return 0;
}
Output
This is my string
Assignment statements
In C, assignment operators are used to assign values to variables. The left operand is the variable and the right
operand is the value being assigned. The value on the right must match the data type of the variable
otherwise, the compiler will raise an error.
Example:
int main() {
// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("%d", a);
return 0;
}
Output
10
Explanation: In the above example, the assignment operator (=) is used to assign the value 10 to the
variable a. The printf() function then prints the value of a, which is 10, to the console.
Syntax
variable = value;
Example:
#include <stdio.h>
int main() {
int x = 22;
// Assigning value 10 to a
// using "=" operator
int a = x;
printf("%d", a);
return 0; }
Output
22
These statements evaluate one or more conditions and make the decision whether to execute a block of
code or not.
For example, consider that there is a show that starts only when certain number of people are present
in the audience.
Example:
#include <stdio.h>
int main() {
// Number of people in the audience
int num = 100;
// Conditional code inside decision making statement
if (num > 50) {
printf("Start the show");
}
return 0;
}
Output
The expression inside () parenthesis is the condition and set of statements inside {} braces is its body. If the
condition is true, only then the body will be executed.
If there is only a single statement in the body, {} braces can be omitted.
2. if-else in C
The if statement alone tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t. But what if we want to do something else when the condition is false? Here comes
the C else statement. We can use the else statement with the if statement to execute a block of code when the
condition is false. The if-else statement consists of two blocks, one for false expression and one for true
expression.
Example
#include <stdio.h>
int main() {
int i = 10;
if (i > 18) {
printf("Eligible for vote");
}
else {
printf("Not Eligible for vote");
}
return 0;
}
Output
The block of code following the else statement is executed as the condition present in the if statement is false.
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if
statement inside another if statement. Yes, C allow us to nested if statements within if statements, i.e, we can
place an if statement inside another if statement.
Example
#include <stdio.h>
int main(){
int i = 10;
if (i == 10) {
if (i < 18)
printf("Still not eligible for vote");
else
printf("Eligible for vote\n");
}
else {
if (i == 20) {
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}
return 0;
}
Output
4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed. if-else-if ladder is similar to the switch statement.
Example
#include <stdio.h>
int main() {
int i = 20;
Output
5. switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement.
The switch block consists of cases to be executed based on the value of the switch variable.
Example
int main() {
// variable to be used in switch statement
int var = 18;
// declaring switch cases
switch (var) {
case 15:
printf("You are a kid");
break;
case 18:
printf("Eligible for vote");
break;
default:
printf("Default Case is executed");
break;
}
return 0;
}
Output
Note: The switch expression should evaluate to either integer or character. It cannot evaluate any other data
type.
6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else statement.
It is also known as the ternary operator as it works on three operands.
Example:
#include <stdio.h>
int main() {
int var;
int flag = 0;
7. Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the functions in a program.
They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is encountered from
within a loop, the loop iterations stop there, and control returns from the loop immediately to the first
statement after the loop.
Example
#include <stdio.h>
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6 };
int key = 3;
int size = 6;
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
} }
return 0;
}
Output
B) Continue
This loop control statement is just like the break statement. The continue statement is opposite to that
of the break statement, instead of terminating the loop, it forces to execute the next iteration of the
loop.
As the name suggests the continue statement forces the loop to continue or execute the next iteration.
When the continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
Example:
#include <stdio.h>
int main() {
1 2 3 4 5 7 8 9 10
C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to jump from one
point to another within a function.
Examples:
#include <stdio.h>
int main() {
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
D) return
The return in C returns the flow of the execution to the function from where it is called. This statement
does not mandatorily need any conditional statements.
As soon as the statement is executed, the flow of the program stops immediately and returns the
control from where it was called. The return statement may or may not return anything for a void
function, but for a non-void function, a return value must be returned.
Example:
#include <stdio.h>
int sum(int a, int b) {
int s1 = a + b;
return s1;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sumOf = sum(num1, num2);
printf("%d", sumOf);
return 0;
}
Output
20
Preprocessor directives
In C programming, the preprocessor is a program that process the source code before the actual
compilation begins.
It uses preprocessor directives are commands that instruct the preprocessor to perform specific
actions. These directives start with the #
List of Preprocessor Directives
#define
In C, the #define preprocessor directive is used to define the macros and symbolic constants.
The macros are the identifiers defined by #define which are replaced by their value before
compilation.
Example:
#include <stdio.h>
// Defining a macro for PI
#define PI 3.14159
int main()
{
// Using the PI macro to calculate
double r = 8.0;
10double area = PI * r * r;
printf("%f\n", a);
return 0;
}
Output
201.067
#include
#include preprocessor directive is used to include the contents of a specified file into the source code
before compilation.
It allows you to use functions, constants, and variables from external libraries or header files. There
are two types:
#include <file_name>
#include "filename"
Here, file inclusion with double quotes ( ” ” ) tells the compiler to search for the header file in the
directory of source file while <> is used for system libraries.
Example:
Example
Let us consider the following source code in C languge (main.c)
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello World! \n");
return 0; }
Output
Hello World!
Explanation:
The ".c" is a file extension that usually means the file is written in C. The first line is the preprocessor
directive #include that tells the compiler to include the stdio.h header file. The text inside /* and */ are
comments and these are useful for documentation purpose.
The entry point of the program is the main() function. It means the program will start by executing the
statements that are inside this functions block.
Here, in the given program code, there are only two statements: one that will print the sentence "Hello
World" on the terminal, and another statement that tells the program to "return 0" if it exited or ended
correctly. So, once we compiled it, if we run this program we will only see the phrase "Hello World"
appearing.
What Goes Inside the C Compilation Process?
In order for our "main.c" code to be executable, we need to enter the command "gcc main.c", and the compiling
process will go through all of the four steps it contains.
Step 1: Preprocessing
The preprocessor performs the following actions −
Step 3: Assembling
The assembler takes the IR code and transforms it into object code, that is code in machine language
(i.e. binary). This will produce a file ending in ".o".
We can stop the compilation process after this step by using the option "-c" with the gcc command, and
pressing Enter.
Note that the "main.o" file is not a text file, hence its contents won't be readable when you open this file
with a text editor.
Step 4: Linking
The linker creates the final executable, in binary. It links object codes of all the source files together.
The linker knows where to look for the function definitions in the static libraries or the dynamic
libraries.
Static libraries are the result of the linker making a copy of all the used library functions to the
executable file. The code in dynamic libraries is not copied entirely, only the name of the library is
placed in the binary file.
By default, after this fourth and last step, that is when you type the whole "gcc main.c" command
without any options, the compiler will create an executable program called [Link] (or [Link] in
case of Windows) that we can run from the command line.
We can also choose to create an executable program with the name we want, by adding the "-o" option
to the gcc command, placed after the name of the file or files we are compiling.