Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

c Programming Complete Notes

The document is a comprehensive tutorial on the C programming language, detailing its history, benefits, and applications. It covers fundamental concepts such as variables, data types, and variable classification, providing examples and rules for naming variables. Additionally, it includes a simple C program to demonstrate basic syntax and functionality.

Uploaded by

Soham sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

c Programming Complete Notes

The document is a comprehensive tutorial on the C programming language, detailing its history, benefits, and applications. It covers fundamental concepts such as variables, data types, and variable classification, providing examples and rules for naming variables. Additionally, it includes a simple C program to demonstrate basic syntax and functionality.

Uploaded by

Soham sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 175

C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

What is C?
It is a very powerful and general-purpose language used in programming. We can use C to develop
software such as databases, operating systems, compilers, and many more. This programming
language is excellent to learn for beginners in programming.
About C Programming
The C language is imperative, procedural, and general-purpose in
nature, developed by Dennis M. Ritchie in 1972 at the Bell
Telephone for developing the UNIX OS. As of now, the C language
is one of the most widely used computer languages along with Java,
which is mostly used among modern programmers.
Benefits of C Programming Language
Here are a few reasons why programmers choose the C language for
running a program:
 It is a structured language.
 The C language is very easy to understand and learn.
 The C language generates very efficient programs.
 It helps you handle various low-level activities.
 The compilation of C programs can occur on various computer programs.
Facts About the C Language
 The C language came into existence for writing an OS known as the UNIX operating system.
 This language is the successor of the B
language, which came into existence in the
early 1970s.
 The ANSI (American National Standard
Institute) formalized this language in 1988.
 The creators of this language have totally
written the UNIX OS in C.
 As of today, the C language is the most
popular and widely used programming
language.
 Programmers have implemented a majority of the futuristic, avant-garde tools and software
using the C language.

Writing the word “How are you” using a C Program

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Excited about learning the basics of the C language? Well, you should be. Take a look at a small
conventional program written in the C language that prints the phrase, “How are you” in the
output.

#include <stdio.h>

int main()

/* your first programming in C language */

printf(“How are you \n”);

return 0;

Applications of a C Program
This language was initially utilized for the development of systems- particularly those programs that
would make up an OS (operating system). The C programming language was adopted in the form of a
language for system development since it generates codes that run as fast as those codes that exist in
the assembly language. Here are a few examples of how we can use the C language in development:
 Language Compilers
 Operating Systems
 Text Editors
 Assemblers
 Network Drivers
 Print Spoolers
 Modern Programs
 Language Interpreters
 Databases
 Utilities
Uses of the C Programming Language
 Procedural Language: The execution of the instructions present in a C program happens
step by step.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 Speed: The C language is much faster as compared to a majority of the programming


languages, such as Python, Java, and many more.
 Portable: A C program can be moved from any given platform to another one, and we can
also run it on that platform without any of the charges.
 General Purposes: We can use the C programming language for developing operating
systems, databases, embedded systems, etc.
Variables in C

Variable is basically nothing but the name of a


memory location that we use for storing data. We
can change the value of a variable in C or any
other language, and we can also reuse it multiple
times. We use symbols in variables for
representing the memory location- so that it
becomes easily identifiable by any user.

Use of the Variables in C

Variables are the storage areas in a code that the


program can easily manipulate. Every variable in C language has some specific type- that determines
the layout and the size of the memory of the variable, the range of values that the memory can hold,
and the set of operations that one can perform on that variable.

The name of a variable can be a composition of digits, letters, and also underscore characters. The
name of the character must begin with either an underscore or a letter. In the case of C, the lowercase
and uppercase letters are distinct. It is because C is case-sensitive in nature. Let us look at some more
ways in which we name a variable.

Rules for Naming a Variable in C

We give a variable a meaningful name when we create it. Here are the rules that we must
follow when naming it:

1. The name of the variable must not begin with a digit.

2. A variable name can consist of digits, alphabets, and even special symbols such as an
underscore ( _ ).

3. A variable name must not have any keywords, for instance, float, int, etc.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

4. There must be no spaces or blanks in the variable name.

5. The C language treats lowercase and uppercase very differently, as it is case sensitive. Usually,
we keep the name of the variable in the lower case.

Let us look at some of the examples,

int var1; // it is correct

int 1var; // it is incorrect – the name of the variable should not start using a number

int my_var1; // it is correct

int my$var // it is incorrect – no special characters should be in the name of the variable

char else; // there must be no keywords in the name of the variable

int my var; // it is incorrect – there must be no spaces in the name of the variable

int COUNT; // it is a new variable

int Count; // it is a new variable

int count; // it is a valid variable name

Data Type of the Variable

We must assign a data type to all the variables that are present in the C language. These define the
type of data that we can store in any variable. If we do not provide the variable with a data type,
the C compiler will ultimately generate a syntax error or a
compile-time error.

The data Types present in the C language are float, int,


double, char, long int, short int, etc., along with other
modifiers.

Types of Primary/ Primitive Data Types in C


Language

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The variables can be of the following basic types, based on the name and the type of the variable:

Type of Name Description Uses


Variable

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

char Character It is a type of integer. It We use them in the form of single


is typically one byte alphabets, such as X, r, B, f, k, etc.,
(single octet). or for the ASCII character sets.

int Integer It is the most natural We use this for storing the whole
size of an integer used numbers, such as 4, 300, 8000, etc.
in the machine.

float Floating- It is a floating-point We use these for indicating the real


Point value that is single number values or decimal points,
precision. such as 20.8, 18.56, etc.

double Double It is a floating-point These are very large-sized numeric


value that is double values that aren’t really allowed in
precision. any data type that is a floating-point
or an integer.

void Void It represents that there We use it to represent the absence of


is an absence of type. value. Thus, the use of this data type
is to define various functions.

Let us look at a few examples,


// int type variable in C
int marks = 45;
// char type variable in C
char status = ‘G’;
// double type variable in C
double long = 28.338612;
// float type variable in C
float percentage = 82.5;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

If we try to assign a variable with an incorrect value of datatype, then the compiler will (most
probably) generate an error- the compile-time error. Or else, the compiler will convert this value
automatically into the intended datatype of the available variable.
Let us look at an example,
#include <stdio.h>
int main() {
// assignment of the incorrect value to the variable
int a = 20.397;
printf(“Value is %d”, a);
return 0;
}
The output generated here will be:
20
As you can already look at this output- the compiler of C will remove the part that is present after the
decimal. It is because the data types are capable of storing only the whole numbers.
We Cannot Change The Data Type
Once a user defines a given variable with any data type, then they will not be able to change the data
type of that given variable in any case.
Let us look at an example,
// the int variable in C
int marks = 20;
float marks; // it generates an error
Variable Definition in C
The variable definition in C language tells the compiler about how much storage it should be creating
for the given variable and where it should create the storage. Basically, the variable definition helps in
specifying the data type. It contains a list of one variable or multiple ones as follows:
type variable_list;
In the given syntax, type must be a valid data type of C that includes w_char, char, float, int, bool,
double, or any object that is user-defined. The variable_list, on the other hand, may contain one or
more names of identifiers that are separated by commas. Here we have shown some of the valid
declarations:
char c, ch;
int p, q, r;
double d;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

float f, salary;
Here, the line int p, q, r; defines as well as declares the variables p, q, and r. It instructs the compiler to
create three variables- named p, q, and r- of the type int.
We can initialize the variables in their declaration (assigned an initial value). The initializer of a
variable may contain an equal sign- that gets followed by a constant expression. It goes like this:
type variable_name = value;
A few examples are −
extern int p = 3, q = 5; // for the declaration of p and q.
int p = 3, q = 5; // for the definition and initialization of p and q.
byte x = 22; // for the definition and initialization of x.
char a = ‘a’; // the variable x contains the value ‘a’.
In case of definition without the initializer: The variables with a static duration of storage are
initialized implicitly with NULL (here, all bytes have a 0 value), while the initial values of all the
other variables are not defined.
Declaration of Variable in C
Declaring a variable provides the compiler with an assurance that there is a variable that exists with
that very given name. This way, the compiler will get a signal to proceed with the further compilation
without needing the complete details regarding that variable.
The variable definition only has a meaning of its own during the time of compilation. The compiler
would require an actual variable definition during the time of program linking.
The declaration of variables is useful when we use multiple numbers of files and we define
the variables in one of the files that might be available during the time of program linking. We
use the extern keyword for declaring a variable at any given place. Though we can declare one
variable various times in a C program, we can only define it once in a function, a file, or any block of
code.
Example
Let us look at the given example where we have declared the variable at the top and initialized and
defined them inside the main function:
#include <stdio.h>
// Declaration of Variable
extern int p, q;
extern int c;
extern float f;
int main () {
/* variable definition: */
int p, q;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

int r;
float i;
/* actual initialization */
p = 10;
q = 20;
r = p + q;
printf(“the value of r : %d \n”, r);
i = 70.0/3.0;
printf(“the value of i : %f \n”, i);
return 0;
}
The compilation and execution of the code mentioned above will produce the result as follows:
the value of r : 30
the value of i : 23.333334

Classification of Variables in C
The variables can be of the following basic types, based on the name and the type of the
variable:
 Global Variable: A variable that gets declared outside a block or a function is known
as a global variable. Any function in a program is capable of changing the value of a
global variable. It means that the global variable will be available to all the functions in the
code. Because the global variable in c is available to all the functions, we have to declare it at
the beginning of a block. Explore, Global Variable in C to know more.
Example,
int value=30; // a global variable
void function1(){
int a=20; // a local variable
}
 Local Variable: A local variable is a type of variable that we declare inside a block or a
function, unlike the global variable. Thus, we also have to declare a local variable in c at the
beginning of a given block.
Example,
void function1(){
int x=10; // a local variable
}
A user also has to initialize this local variable in a code before we use it in the program.
 Automatic Variable: Every variable that gets declared inside a block (in the C language)
is by default automatic in nature. One can declare any given automatic variable explicitly

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

using the keyword auto.


Example,
void main(){
int a=80; // a local variable (it is also automatic variable)
auto int b=50; // an automatic variable
}
 Static Variable: The static variable in c is a variable that a user declares using
the static keyword. This variable retains the given value between various function calls.
Example,
void function1()
{
int a=10; // A local variable
static int b=10; // A static variable
a=a+1;
b=b+1;
printf(“%d,%d”,a,b);
}
If we call this given function multiple times, then the local variable will print this very same
value for every function call. For example, 11, 11, 11, and so on after this. The static variable, on
the other hand, will print the value that is incremented in each and every function call. For example,
11, 12, 13, and so on.
 External Variable: A user will be capable of sharing a variable in multiple numbers of source
files in C if they use an external variable. If we want to declare an external variable, then we
need to use the keyword extern.
Syntax, extern int a=10;// external variable (also a global variable)
Rvalues and Lvalues in C
There are two types of expressions in the C language:
rvalue − This term refers to the data value that gets stored at some type of memory address. The
rvalue is basically an expression that has no value assigned to it. It means that an rvalue may appear
on the RHS (right-hand side), but it cannot appear on the LHS (left-hand side) of any given
assignment.
lvalue − lvalue expressions are the expressions that refer to any given memory location. The lvalue
can appear as both- the RHS as well as the LHS of any assignment.
A variable is an lvalue. Thus, it may appear on the LHS of an assignment as well, along with the RHS.
The numeric literals are rvalues. Thus, these might not be assigned. Thus, these can’t appear on
the LHS. Here are two statements- one valid and invalid:
Example,
int g = 10; // a valid statement

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

30 = 60; // an invalid statement; will generate a compile-time error


Static variable in c
A static variable possesses the property of preserving its actual value even after it is out of its scope.
Thus, the static variables are able to preserve their previous value according to their previous scope,
and one doesn’t need to initialize them again in the case of a new scope.
Syntax and Use of the Static Variable in C
We only need to initialize the static variables once. Thus, the compiler will persist with the given
variable till we reach the end of our given program. One can define a static variable both- outside or
inside the function. These are local to the block, and their default value is always zero. The static
variables stay alive till the program gets executed in the end.
The syntax of the static variables in C is:
static datatype variable_name = value;
In this case,
value − It refers to the value that we use to initialize the variable. It is zero, by default.
variable_name − It refers to the name that any user gives to a variable.
datatype − It refers to the datatype of the variable here, such as char, float, int, etc.

Example of Static Variable in C


#include <stdio.h>
int main() {
auto int x = -30;
static int y = 16;
printf(“Value of the given auto variable is : %d\n”, x);
printf(“Value of the given static variable y is : %d\n”,y);
if(x!=0)
printf(“Sum of the auto variable and static variable is :
%d\n”,(x+y));
return 0;
}
Output
The output generated here would be:
Value of the auto variable is : -30
Value of the static variable y is : 16

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Sum of the auto variable and static variable is : -18


Use of the Static Variable keyword
We use the static variable keyword in the following given situations:
Static Local Variable – When we declare a local variable with a static keyword, it is called a static
local variable. The static local variable’s memory stays valid throughout any program. But the scope
of the visibility of these variables is similar to that of the automatic local variables. But when the
static local variable gets modified by the function during the first function call, the modified value
here will also be available for the next function.
Static Global Variable – When we declare a global variable with a static keyword, then it is called a
static global variable. This variable gets declared at the top of any program. Added to this, its
visibility stays throughout any program.
Static Member Variables – When we declare the member variables with a static keyword in a
class, we call them static member variables. All the instances present in a class can easily access
this type of variables, and we don’t require a specific instance to do that.
Some Important Points to Remember
1. The static int variable stays in a given memory when the program is still running, while an auto
variable or a normal variable gets destroyed when the function call in which the variable got declared
is over.
For instance, one can utilize the static int for counting the total number of times a function gets called,
but they can’t use an auto variable for the very same purpose.
2. The memory allocation of static variables is not in the stack segment, but in the data segment.
3. The static variables are initialized as 0 (just like global variables) if it is not initialized explicitly.
For instance, the value of p in the below program will get printed as 0, while for q, the value is
something garbage.
#include <stdio.h>
int main()
{
static int p;
int q;
printf(“%d \n %d”, p, q);
}
Output
The output generated will be:
0
some_garbage_value

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

4. The static variables in the C language can be initialized only by using constant literals. Note that the
very same condition is not applicable in the C++ language. Thus, if you save this program as a C++
one, the compilation and running of the program would go just fine.
5. The static global functions, as well as variables, are also possible with the C and C++ languages.
The reason why we use these is for limiting the scope of any function or variable to a file.
6. We must never declare the static variables inside the structure. The primary reason here is that the C
compiler requires placing the entire structure elements together. It means that the memory allocation
for the structure members must be contagious. It is possible to allocate the memory dynamically (i.e.,
heap segment), declare the structure inside a function (i.e., stack segment), or it can even be global
(data segment or BSS). Whatever the case here, all the structure members must reside inside the same
segment of memory. It is because we fetch the value for the structure element by counting the
element’s offset from the initial address of a structure. The separation of just one member alone to the
data segment defeats the very purpose of the static variable and then it becomes possible for us to
have the entire structure be static.
Global variable in c
The variables that are declared outside the given function are known as global variables. These
do not stay limited to a specific function- which means that one can use any given function to not
only access but also modify the global variables. The initialization of these variables occurs
automatically to 0 during the time of declaration. Also, we generally write the global variables before
the main() function.
Use of the Global Variable in C
The global variables get defined outside any function- usually at the very top of a program. After this,
the variables hold their actual values throughout the lifetime of that program, and one can access them
inside any function that gets defined for that program.
As already stated earlier, any function can access a global variable. It means that once you declare a
program, its global variable will be available for use throughout the running of the entire program.
Example of Global Variable in C
Here is a program that shows how we use global variables practically:
#include<stdio.h>
void func_a();
void func_b();
int x, y = 10; // declaration and initialization of global variables here
int main()
{
printf(“The Global x is = %d\n”, x);
printf(“The Global y is = %d\n\n”, y);
func_a();
func_b();

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

// a signal to the operating system that the program ran fine here
return 0;
}
void func_a()
{
printf(“From the func_a() the Global x is = %d\n”, x);
printf(“From the func_a() the Global y is = %d\n\n”, y);
}
void func_b()
{
int x = 5;
printf(“Inside the func_b() x is = %d\n”, x);
}
Output
The output obtained here will be:
The Global x is = 0
The Global y is = 10
From the func_a() the Global x is = 0
From the func_a() the Global y is = 10
Inside the func_b() x is = 5
You can notice that in line 4, x and y get declared as two of the global variables of the type int. Here,
the variable x will get initialized automatically to 0. Then one can use variables like x and y inside any
of the given functions. Also notice that inside the func_2() function, there exists a local variable that
has the same name as the global variable. When we have a conflict between the local and global
variables, then the precedence is for the local variable. That’s why the value of the local variable
x gets printed inside the func().
The global variables, unlike the local variables, do not get destroyed with the end of a function.
These are available for any function till the end of the execution of the program- thus named
global.
How Does One Use Global Variables in C?
The global variables solve some very specific problems as it makes the declaration of the variable
universal. This is the reason why any function present anywhere in a program becomes capable of
accessing the variable. Thus, we do not need to pass or return it from a function.
To understand how we declare and use a global variable, you can toss around your age.
The age and float global variables get affected by both the functions. We can pass them through the

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

function, but cannot get their values in return (the C functions can return only a single value). Thus, in
such cases, we use the global variable as a viable solution.
Redeclaration of Global Variable in C
The C language allows the redeclaration of the global variable. It means that this variable can
get declared again when the first declaration doesn’t lead to the initialization of the variable.
Look at the two programs given below:
// First Program
int main()
{
int a;
int a = 7;
printf(“%d”, a);
return 0;
}
The output obtained in the C language will be:
redeclaration of ‘a’ with no linkage
// Second Program
int a;
int a = 7;
int main()
{
printf(“%d”, a);
return 0;
}
The output obtained in the C language will be:
7
It is possible because the second program works pretty well in the C language even if the first one
fails during compilation. On the other hand, in the C++ language, both of these programs fail during
the time of compilation.
Let us look at another program below that fails in C, as the initialization of the global variable occurs
in the first declaration itself.
int a = 15;
int a = 30;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

int main()
{
printf(“%d”, a);
return 0;
}
The output obtained here would be:
error: redefinition of ‘a’

A constant is a name given to the variable whose values can’t be altered or changed. A constant
is very similar to variables in the C programming language, but it can hold only a single variable
during the execution of a program. It means that once we assign value to the constant, then we can’t
change it throughout the execution of a program- it stays fixed.

Use of the Constants in C


A constant is basically a named memory location in a program that holds a single value throughout the
execution of that program. It can be of any data type- character, floating-point, string and double,
integer, etc. There are various types of constants in C. It has two major categories- primary and
secondary constants. Character constants, real constants, and integer constants, etc., are types of
primary constants. Structure, array, pointer, union, etc., are types of secondary constants.
What are Literals in C?
Literals are referred to as the values that we assign to the variables that remain constant throughout
the execution of a program. Generally, we can use both the terms- literal and constants
interchangeably. For instance, the expression “const int = 7;”, is a type of constant expression, while
we refer to the value 7 as a constant integer literal.

Types of Constants in C

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Type of Constants Data type Example of Data type

Integer constants
int unsigned int 2000u, 5000U, etc.

23, 738, -1278, etc.


long int, long long int 325,647 1,245,473,940

Floating-point or Real constants


doule float 20.987654

500.987654321

Octal constant int Example: 013 /*starts with 0 */

Hexadecimal constant int Example: 0x90 /*starts with 0x*/

character constants char Example: ‘X’, ‘Y’, ‘Z’

string constants char Example: “PQRS”, “ABCD”

More About Types of Constants in C


Integer Constants
It can be an octal integer or a decimal integer or even a hexadecimal integer. We specify a decimal
integer value as a direct integer value, while we prefix the octal integer values with ‘o’. We also prefix
the hexadecimal integer values with ‘0x’.
The integer constant used in a program can also be of an unsigned type or a long type. We suffix the
unsigned constant value with ‘u’ and we suffix the long integer constant value with ‘l’. Also, we suffix
the unsigned long integer constant value using ‘ul’.
Examples,
55 —> Decimal Integer Constant
0x5B —> Hexa Decimal Integer Constant
O23 —> Octal Integer Constant
68ul —> Unsigned Long Integer Constant
50l —> Long Integer Constant

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
18
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

30u —> Unsigned Integer Constant


Floating Point Constants / Real Constants
This type of constant must contain both the parts- decimal as well as integers. Sometimes, the
floating-point constant may also contain the exponential part. In such a case when the floating-point
constant gets represented in an exponential form, its value must be suffixed using ‘E’ or ‘e’.
Example,
We represent the floating-point value 3.14 as 3E-14 in its exponent form.
Character Constants
The character constants are symbols that are enclosed in one single quotation. The maximum length of
a character quotation is of one character only.
Example,
‘B’
‘5’
‘+’
Some predefined character constants exist in the C programming language, known as escape
sequences. Each escape sequence consists of a special functionality of its own, and each of these
sequences gets prefixed with a ‘/’ symbol. We use these escape sequences in output functions known
as ‘printf()’.
String Constants
The string constants are a collection of various special symbols, digits, characters, and escape
sequences that get enclosed in double quotations.
The definition of a string constant occurs in a single line:
“This is Cookie”
We can define this with the use of constant multiple lines as well:
” This\
is\
Cookie”
The definition of the same string constant can also occur using white spaces:
“This” “is” “Cookie”
All the three mentioned above define the very same string constant.
Rules of Constructing Constants in C
Here is how we construct these constants in a given program:
Integer Constants
 It must have at least one digit.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
19
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 There must be no decimal point.


 It does not allow any blanks or commas.
 An integer constant can be both negative or positive.
 We assume an integer constant to be positive if there is no sign in front of that constant.
 The allowable range for this type of constant is from -32768 to 32767.
Real Constants
 This type of constant must consist of one digit at least.
 There must not be any decimal point.
 This type of constant can be both negative or positive.
 It does not allow any blanks or commas within.
 We assume an integer constant to be positive if there is no sign in front of that constant.
String and Character Constants
 This type of constant can be a single digit, a single alphabet, or even a single special symbol
that stays enclosed within single quotes.
 The string constants get enclosed within double quotes.
 The maximum length of this type of constant is a single character.
Backslash Character Constants
 These are some types of characters that have a special type of meaning in the C language.
 These types of constants must be preceded by a backslash symbol so that the program can use
the special function in them.
 Here is a list of all the special characters used in the C language and their purpose:

Meaning of Character Backslash Character

Backspace \b

New line \n

Form feed \f

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
20
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Horizontal tab \t

Carriage return \r

Single quote \’

Double quote \”

Vertical tab \v

Backslash \\

Question mark \?

Alert or bell \a

Hexadecimal constant (Here, N – hex.dcml cnst) \XN

Octal constant (Here, N is an octal constant) \N

Creation and Use of Constants in C


We can create constants in the C programming language by using two of the concepts mentioned
below:
 By using the ‘#define’ preprocessor
 By using the ‘const’ keyword.
Use of the ‘const’ Keyword

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
21
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The ‘const’ keyword is used to create a constant of any given datatype in a program. For creating a
constant, we have to prefix the declaration of the variable with the ‘const’ keyword. Here is the
general syntax that we follow when using the ‘const’ keyword:
const datatype constantName = value ;
OR
const datatype constantName ;
Let us look at an example to understand this better
const int a = 10 ;
In this case, a is an integer constant that has a fixed value of 10.
The program will run as follows:
#include<stdio.h>
#include<conio.h>
void main(){
int q = 9 ;
const int a = 10 ;
q = 15 ;
a = 100 ; // creates an error
printf(“q = %d\na = %d”, q, a ) ;
}
The program given above creates an error. It is because we are trying to change the value of the
constant variable (a = 100).
Use of the ‘#define’ preprocessor
One can also use the ‘#define’ preprocessor directive to create the constants. And when we create the
constants by making use of the preprocessor directive, we must define it in the very beginning of
the program. It is because we must write all the preprocessor directives before the global
declaration.
Here is the syntax that we must use for creating a constant by making use of the ‘#define’
preprocessor directive:
#define CONSTANTNAME value
Let us look at an example to understand this better,
#define PI 3.14
In this above-mentioned case, PI is a constant, and it has a value of 3.14.
We can run a program for this as follows:
#include<stdio.h>

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
22
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

#include<conio.h>
#define PI 3.14
void main(){
int a, area ;
printf(“Enter the radius of the given circle here : “) ;
scanf(“%d”, &a) ;
area = PI * (a * a) ;
printf(“The area of the circle is = %d”, area) ;
}
Data types in C
Just like the name suggests, here, data types refer to the type of data that we are using in a C program.
Whenever we utilise a data type in a C program, we define the variables or functions used in it. We do
so because we must specify the type of data that is in use, so that the compiler knows exactly what
type of data it must expect from the given program.
Purpose of Data Types in C
Data types used in C language refer to an extensive system that we use to declare various types of
functions or variables in a program. Here, on the basis of the type of variable present in a program, we
determine the space that it occupies in storage, along with the way in which the stored bit pattern will
be interpreted.
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
Example of Data Types in C
Let us take a look at an example to understand data types better.
For instance, we may want to utilise some numbers such as 5, 8, 600, or maybe a decimal point
number such as 43.59, 127.368, 271.49, or maybe a text such as “cappuccino”. Then, the compiler
used in C language would handle all of these very differently. Thus, here, we use different data types
for defining what data types we want in the program.
Types of Data Types in C
Here are the five major categories into which data types are divided in C language:

Data Type Example of Data Type

Basic Data Type Floating-point, integer, double, character.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
23
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Derived Data Type Union, structure, array, etc.

Enumerated Data Type Enums

Void Data Type Empty Value

Bool Type True or False

The basic data types are also known as the primary data types in C programming.
Primary Data Types in C
Here are the five primitive or primary data types that one can find in C programming language:
1. Integer – We use these for storing various whole numbers, such as 5, 8, 67, 2390, etc.
2. Character – It refers to all ASCII character sets as well as the single alphabets, such as ‘x’,
‘Y’, etc.
3. Double – These include all large types of numeric values that do not come under either floating-
point data type or integer data type. Visit Double Data Type in C to know more.
4. Floating-point – These refer to all the real number values or decimal points, such as 40.1, 820.673,
5.9, etc.
5. Void – This term refers to no values at all. We mostly use this data type when defining the functions
in a program.
Various keywords are used in a program for specifying the data types mentioned above. Here are the
keywords that we use:

Keyword Used Data Type

int Integer

float Floating-point

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
24
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

void Void

char Character

double Double

The size of every data type gets defined in bytes/ bits. Also, these data types are capable of holding a
very wide range of values.
Different Data Type Values
The size of any given data type in a program depends a lot on the type of processor, as well as the
compiler. In simpler words, the size of the data type depends entirely on the computer on which we
run C language along with the version of the C program compiler that we installed in the computer.
The int data type can be 4 bytes/ 2 bytes.
Remembering the size of the int data type is very easy. The given size is generally equal to the length
of the word of the program’s execution environment. In other words, int will be 2 bytes or 16 bits in
the case of an environment that is 16-bit. However, int will be 4 bytes or 32 bits in case of an
environment that is 32-bit.
The char data type is 1 byte.
The size of the char data type is basically 8 bits or 1 byte. No variation would occur with different
compilers and interpreters. It means that the type of compiler or processor used will have no effect
on its size whatsoever.

The double data type is 8 bytes.


The size of the double data type is basically 64 bits or 8 bytes. It is capable of storing values that
are comparatively double the size of the bytes that the float data type can store. This is the reason why
it is known as the double.
When looking at the 64 bits in total, the program has 1 bit for the sake of sign representation, the
exponent uses 11 bits, and it uses the remaining 52 bits for the mantissa.
This data type is capable of holding about 15-17 digits, both after and before the decimal of the data
type.
The float data type is 4 bytes.
The size of the float data type is basically 32 bits or 4 bytes. The float data type is single-precision in
nature, and we use it for holding the decimal values. It helps in the storage of various large values, but
the float is comparatively faster than double. It is because double works with comparatively much
larger data values. Thus, it is slower comparatively.
The void data type is 0 bytes.
Since the void data type has no meaning, it has no size at all.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
25
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

There is a range of values that come under all of these data types. But before we look into that, let us
take a look at the modifiers that are used in the data types.
Data Type Modifiers in C Programming Language
There are basically four types of modifiers for all data types used in C language. We use these along
with all the basic data types for categorising them further.
For instance, if we say that there is a chocolate bar on the table, the person we are speaking to will
know that a chocolate bar is present on the table. But if we get more specific and say that there is a
dark chocolate bar on the table or a milk chocolate bar on the table, it will become much more clear
and specific, to the person who is listening.
In a very similar manner, the modifiers in C language help in making the primary or primitive data
types much more specific.
Here are a few modifiers:
 short
 long
 unsigned
 signed
Just like the names suggest here, we use the unsigned and signed modifiers for presenting the
unsigned (only +) and signed (- and +) values in any given data type. Also, the short and long
modifiers cause an effect on the value range of any given data type.
For instance, the long int, short int, unsigned int, signed int, etc., are all very valid data types in the C
programming language.
Now, if we combine all the modifiers mentioned above with the five primitive or primary data types,
then it will result in the formation of the following data types:
Range of Values of C Data Type
The range of all the C language data types are present in the table given below:

Data Type Format Minimal Range Typical Bit


Specifier Size

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
26
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
unsigned char %c 0 to 255 8
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
27
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
char %c -127 to 127 8
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
28
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
signed char %c -127 to 127 8
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
29
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
int %d, %i -32,767 to 32,767 16 or 32
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
30
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
unsigned int %u 0 to 65,535 16 or 32
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
31
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
signed int %d, %i Same as int Same as int
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
32
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT 16 or 32
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
33
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
short int %hd -32,767 to 32,767 16
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
34
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

unsigned short %hu 0 to 65,535 16


int

signed short int %hd Same as short int 16

long int %ld, %li -2,147,483,647 to 2,147,483,647 32

long long int %lld, %lli -(263 – 1) to 263 – 1 (It will be added by the C99 64
standard)

signed long int %ld, %li Same as long int 32

unsigned long %lu 0 to 4,294,967,295 32


int

unsigned long %llu 264 – 1 (It will be added by the C99 standard) 64
long int

float %f 1E-37 to 1E+37 along with six digits of the 32


precisions here

double %lf 1E-37 to 1E+37 along with six digits of the 64


precisions here

long double %Lf 1E-37 to 1E+37 along with six digits of the 80
precisions here

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
35
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

As you can witness in the table given above, the varied ranges and combinations of the modifiers and
data types result in a range of the changing values.
One must utilise the format specifier when they want to print any value of the variable in a program.
They must do it in the printf() statement.
When the value of the Data Type happens to be out of Range
Whenever we try to assign any value to a given data type in a program that is more than the
allowed value range, then the compiler in C language will generate an error.
Let us look at an example to understand this better.
#include <stdio.h>
int main() {
// the maximum value allowed in the signed short int is 32767
signed short int x = 34767;
return 0;
}
The generated output for this program would be:
warning: very large integer value implicitly truncated to signed type [-Woverflow]
signed short int x = 34767;
^
Whenever we use a type modifier even without using any data type, the program sets the int data type
as a form of default data type. Here, signed would refer to a signed int, unsigned would refer to
unsigned int, short would refer to short int, and also, long would refer to long int.
Meaning of Unsigned as well as Signed
It is basically a bit tricky to understand. But in easier words, the signed modifier would refer to both
the negative and positive values, while the unsigned modifier refers to all of the positive values.
Whenever a compiler happens to get any numeric value, then it converts that very value of the
program into a binary number. This means it will be a combination of various 1s as well as 0s.
For instance, the binary of 1 is 0001 or 01, the binary value of the number 2 will be 0010, for
the number 32767 will be 01111111 11111111, and many more.
When we talk about the signed integers, we use the very first digit starting from the left (in
binary values) or the highest bit of order as the sign flag. The number will be negative whenever the
sign flag is 1. It will, conversely, be positive whenever the sign flag is 0.
And because we use one bit to show if the given number is negative or positive, one less bit will be
representing the number in the program itself. Thus, the range here is very less.
For instance, in the case of a signed int, the binary digit 11111111 11111111 would mean the number -
32,767. Here, the first bit would serve as a sign flag that marks it as a negative number. The rest of the
bits would represent the actual number that is 32767. The very same binary digit 11111111 11111111
would mean 65,535 in the case of an unsigned int.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
36
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Derived Data Types in C


While there are five data types that are primary, various derived data types are also present in C
language that help in storing complex types of data.
Thus, the derived data types are basically primary data types, but these are a bit more grouped
together or twisted, such as a structure, array, pointers, union, etc. Visit Derived Data Types in C to
know more.
Use of C Data Types
The use of C data type is to define the type of data that we use in a program. Let us take a look at each
of these in detail.
The char Data Type
This data type basically refers to all the character values that get enclosed in single quotes. Also, this
data type ranges from -127 to 127.
As we can see, we can use any of the smaller integer values in a char data type.
For instance,
char status = ‘X’
The float Data Type
We use the float data type for storing all the real numbers. These may have both, the exponential part
as well as the decimal part (or the fraction part). It is basically a single-precision type of number.
For instance,
float y = 127.675;
// by using the suffix f or F
float x = 1000.5454F;
Just like the data type int, we can also use the float data type along with various modifiers.
The double Data Type
We store such numbers in a double data type that the float data type can’t store in a program (bigger
than the maximum capacity of the float data type). The double data type is basically a double-
precision type of number. It is capable of holding about 15 to 17 values, both after and before a
decimal point.
For instance,
double y = 424455236424564.24663224663322;
A person will utilise the double data type in a program only when it is needed to store any such large
numbers. Otherwise, we don’t use it as it will make the program very slow.
The int Data Type
We use the int data type for storing the whole numbers that might be values that have no
exponential part or decimal part in the number.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
37
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

We can store the octal (or base 8), hexadecimal (or base 16), and decimal (or base 10) in the data
types.
For instance,
// a simple int data value
int z = 310;
// a negative data value
z = -4260;
// an unsigned int data value that has a suffix of u or U
int z = 90U;
// a long int data value that has a suffix of l or L
long int long_val = 87500L;
When we use the int data type in a program, then we must use the suffix “u” or “U” so that the
compiler can interpret the available value of the unsigned data type. On the other hand, we use the
suffix “l” or “L” when using a long int value in a program.
Basic data types in C :
The basic data types are also known as fundamental or primary data types. Basic data types are used
in the C language for storing the available values in decimal as well as integer forms, and these
provide support for both – unsigned and signed literals.
Why do we use Basic Data Types in C?
All the names – primary, fundamental, and basic data types, mean the very same thing. Let us
suppose that we need to store the details of students, such as their candidate names, IDs, blood groups,
average scores, and total fees. Here, we will use the basic data types for storing this available data.
Here is how we can do it:
char candidate[25];
int id;
char blood;
float scores[5];
double fees;
Types of Basic Data Types in C
The basic data types are of four major types – both in unsigned as well as signed forms. These are:
 Char
 Double
 Float

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
38
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
Data Type Value Range Storage Size

Unsigned int 0 to 65,535 2 bytes

Int (or can be signed int) -32,768 to 32,767 2 bytes

Long int (or it can be signed long int) -2,147,483,648 to 2,147,483,647 4 bytes

Short int (or can be signed short int) -32,768 to 32,767 2 bytes

Unsigned long int 0 to 4,294,967,295 4 bytes

Double 2.3E-308 to 1.7E+308 (about 15 decimal places) 8 bytes

Long double 3.4E-4932 to 1.1E+4932 (about 19 decimal places) 10 bytes

Float 1.2E-38 to 3.4E+38 (about 6 decimal places) 4 bytes

Char (or can be signed char) -128 to 127 1 byte

Unsigned char 0 to 255 1 byte

 Int
The size of memory required for all of these data types can easily change on the basis of what
operating system we are using (64-bit or 32-bit). The table below shows all the data types that we
commonly use in the C programming language, along with their value range and storage size. We will
look into the details according to a 32-bit type of architecture.
Now, let us take a look at all the basic data types in detail.
1. The Integer Data Type
The variables that are of integer type are capable of storing negative, zero, as well as positive
values without the decimals. The C language represents the integer data type by the keyword int.
It can be unsigned as well as a signed value. But in case it is unsigned, then the value assigned to
the integer variable will be considered positive by default.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
39
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

This integer data type has further sub-types named the long int and short int. This can be signed long
int, signed short int, unsigned long int, and unsigned short int. Here, int takes up about 2 bytes or 4
bytes of the storage space and short data type would take up about 2 bytes. The long data type would
take up about 8 bytes and 4 bytes of space in a 64-bit type and 32-bit type operating system
respectively.
Whenever someone tries to assign some decimal values to the int variable, then the value
available after the decimal will get truncated, and a whole number will be left. This whole
number will get assigned to the variable. Let us understand this concept better, by using an
example:
#include
int main() {
int x=11252486;
short int y=10000;
long long num11=51454456154585454;
long num22=499962313469;
printf(“x is %d \n y is %hd \n num11 is %lld \n num22 is %ld \n”,x,y,num11,num22);
return 0;
}
The output generated out of the program mentioned above will be:
x is 11252486
y is 10000
num11 is 51454456154585454
num22 is 1746107133
When performing this arithmetic operation, we may get a decimal value as a result of the
program. In any such case, the variable would discard the numbers after the decimal point, and
accept the whole number only. Also, for the short int variables, the result will be displayed with
an incorrect value if the number we use is bigger than 1000. Always keep that in mind when
assigning a value to the short int variable.
Characteristics of the Integer Data Type:
 We use the int keyword for referring to the integer data type in a C program.
 The int data type would allow a variable in a program to store various numeric values.
 The storage size here would be either 2 bytes, 4 bytes, or even 8 bytes.
 The size would vary a lot on the basis of the processor that is used for running the program.
For instance, when using the 16-bit type of processor, the int data type will be allocated with
about 16 bits or 2 bytes of memory.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
40
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 Similarly, the int data type will be allocated with about 32 bits or 4 bytes in the case of a 32-
bit type of processor, and it will be allocated with 64 bits or 8 bytes of memory for a 64-bit
type of processor.
 The int with 4 bytes of memory is capable of storing values ranging from -2,147,483,648 to
+2,147,483,647.
 The int with 2 bytes of memory is capable of storing values ranging from -32,768 to +32,767.
 In case we want to use an integer value that is crossing the maximum limit for the int, we can
then use the long int or even long long int. These data types have a very high limit for
the values that can be stored.
Important Points to Remember:
 The int data types do not allow us to store the decimal values.
 Whenever we use the int data type for storing the decimal values, the digits present after the
decimals will get truncated. We will only get a whole number as a result.
 In case we don’t want this to happen and would like to store the exact decimal value in the
program’s variable, then we must use the float data type instead.

2. The Floating Point Data Types


We use the floating-point data types for storing the decimal values into a variable in a C program. It is
majorly of two different types:
 Double
 Float
2.1 The Float Data Type
The float variables are used for storing decimal values, and these are capable of storing decimal
values that are present up to 6 digits after the digit’s decimal place. The float variable’s storage size is
about 4 bytes. But its size can vary a lot according to the processors that we use – just like the int data
type. The float values in the C language are represented by a format specifier ‘%f’. The value that
contains the integer value will be printed as well, in the floating type along with redundant zeroes. Let
us look at the example given below to understand this better:
#include
int main() {
float num=67;
float sum=9664.35;
float average=(sum/num);
printf(“The average of numbers is equal to %f \n”, average);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
41
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

printf(“The value of the num is equal to %f \n”,num);


printf(“The value of the num presented as the integer value is equal to %d \n”,num);
}
The program mentioned here will generate an output as follows:
The average is equal to 144.244019
The value of the num is equal to 67.000000
The value of the num presented as the integer value is equal to 0
In case we assign a float variable with an integer value, then we will always get the result to be some
float value that has zeros after the decimal place itself. As already mentioned above, the format
specifier ‘%f’ represents all the float values in a C program. However, if we try printing a float value
with the specifier ‘%d’, then the output of the program mentioned above will not be equal to 67. We
will get a garbage value in the output screen instead.

Characteristics of the Float Data Type:


 The float data type is basically used for storing all the decimal values in a program, but
it has some storage limits.
 The float has a storage size of about 4 bytes. However, it varies a lot on the basis of the
processor present in the CPU in use in the form of int type.
 Using the float data type, we can easily store values that have up to 6 digits after the decimal
point. For instance, one can store the value 12.345678 in a variable if we use the float data
type.
2.2 The Double Data Type
This data type is very similar to that of the float data type. The major difference here is that the double
can contain up to 10 digit values after the decimal place, unlike float that supports only upto 6 digits
after the decimal place. The double data type is represented by the ‘double’ keyword, and we mainly
use it in the case of scientific programs because we require precision here.
Look at the example mentioned below. Here, we have used both – double and float variables. In the
output, the double variable will print the exact assigned value, i.e., ‘349999999.454’. The float
variable, on the other hand, will ultimately mess up with the assigned number. It will print a rounded-
off value in the output. Let us take a look at the program and understand how both of these generate
output accordingly:
#include
int main()
{
float marks=349999999.454;
double score=349999999.454;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
42
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

printf(“The marks obtained by the student is %f \n”,marks);


printf(“The actual score of the student’s exams is %lf”,mean);
return 0;
}
Here is the output that we will get after running the program mentioned above:
The marks obtained by the student is 350000000.000000
The actual score of the student’s exams is
349999999.454000

Characteristics of the Double Data Type:


 This data type is similar to that of the float data type, but it is capable of storing values with
more than 6 digits after the decimal point.
 However, the double data type also has some limits of 10 digits. It means that one can use the
double type for storing those values that have a maximum of 10 digits after the decimal point.
 For instance, you can store the value 90.8765432001 in a variable if we use the double data
type.
 The double data type also has a limited range. It ranges from 1E–37 to 1E+37.
3. The Char Data Type
We use the char data type for storing the single character values – it includes numerical values as well.
Thus, if we create an array of the char data type (character type), it will ultimately become a string.
This string will be capable of storing values like subject, names, etc.
Let us look at an example where we create an array of various characters in the C programming
language:

#include <stdio.h>
int main()
{
char office=’X’;
// for storing a string of various characters in the C programming, we will use an array of all the
characters here
char employee[30]=”Anne”;
printf(“The people are from office %c \n”,office);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
43
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

printf(“The name of the employee is %s”,employee);


return 0;
}
When we use this program in the C language, we will get the output as follows:
The people are from office X
The name of the employee is Anne
Note that the format specifier that we use here for a single character is ‘%c’. On the other hand, if we
try to represent a string or array of all the characters, the format specifier ‘%s’ will represent it in the
program.
Characteristics of the Char Data Type:
 The character data type allows us to store just a single character in a variable in the C
program.
 The storage size of the char data type is about 1 byte.
 The character data type is represented in a program using the ‘char’ data type.
 For instance, we can store ‘X’ with the use of the char data type. But we cannot store more
than one value here, because the char data type won’t support it.
 A string of various characters will be created if we try to create an array of the char data types
in any program. This string will then store every value individually.
Derived data types in c
The derived data types are basically derived out of the fundamental data types. A derived data type
won’t typically create a new data type – but would add various new functionalities to the existing ones
instead.
Uses of Derived Data Types in C
We can derive the derived data types out of the primitive data type by adding some extra relationships
to the elements that are available with the primitive data types. We use the derived data types to
represent multiple values as well as single values in a program.

Types of Derived Data Types in C


The C language supports a few derived data types. These are:
 Arrays – The array basically refers to a sequence (ordered sequence) of a finite number of
data items from the same data type sharing one common name.
 Function – A Function in C refers to a self-contained block of single or multiple statements.
It has its own specified name.
 Pointers – The Pointers in C language refer to some special form of variables that one can
use for holding other variables’ addresses.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
44
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 Unions – The unions are very similar to the structures. But here, the memory that we allocate
to the largest data type gets reused for all the other types present in the group.
 Structures – A collection of various different types of data type items that get stored in a
contagious type of memory allocation is known as structure in C.
*Note – In some of the situations, we can also call the structures and unions to be UDT (User-defined
Data Types).
Arrays

An array is one of the most frequently used data types (derived) in the C language. Thus, when
we create a collection of these data types and store them in the contiguous memory location, they are
known as arrays.
We can create an array with any valid and complete data type. An array type will only get completed
when the types and numbers
of the array members are
implicitly or explicitly
specified. We can complete
the member types in the
same compilation unit or a
different one.
An array is typically used to
perform various operations
on the homogeneous value
sets. The size of any given array depends on the total number of elements present in the array, along
with the data type present in the array. Every element present in an array belongs to the very same
type. For instance,
char a[] = “HEY” /* The declaration of an array a */;
The definition mentioned above would create an array with a total of four characters.
All the elements have a size of 8 bits – about a char object. We determine the size of an array by
its initialization. For instance, in this example, the array that we created consists of three explicit
types of elements along with a null character. Thus, there are four elements. So, a total of four
elements that are about 8 bits each would result in an array that has a total size of about 32 bits. In
simple words, this will be equal to a total of 4 bytes.
The allocation of an array is contiguous in the computer memory. It cannot be empty (empty refers to
having no members). The arrays are capable of having just one dimension. Thus, if we want to create
an array of two dimensions, we have to then declare an array of various arrays (and so on).
For array declaration, it is possible to declare an array with an unknown size. A declaration of this sort
is typically known as an incomplete array declaration. It is named so because the size of the array is
not at all specified. Here is an example that displays an incomplete declaration type:
int a[];
There must be a specification of the size of an array (that we declare this way) elsewhere in any
program that we have with us.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
45
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Structures
The structures also form one of the derived data types in the C language. These are capable of forming
a collection of various dissimilar data types, such as a float, an int, or even an array of char. Thus,
whenever a programmer wants to put various data types
together that are not similar to each other, they can utilise a
structure.
Thus, a structure type refers to a set of various objects that are
sequentially allocated and non-empty. These objects are known
as members. Thus, structures would let a person group
heterogeneous types of data together. Now unlike arrays, all the
elements that constitute a structure do not need to be of the very
same data type. Added to this, one can access all the elements
of a typical structure by their names and not by subscripts. For
instance, the example mentioned below would be used to
declare the student structure, which has two structure variables
(elsa and vin) of the student structure type. Here is how it would look:
struct student { char names[50]; int ages; int studnumber; };
struct student vin, elsa;
The members present in a structure can be of any type, but an incomplete type would be an
exception, for instance, a function type or the void type. A typical structure can consist of
pointers for objects of its type. On the other hand, it cannot have an object of its type in the form
of a member. In case this happens, the object would then be of an incomplete type.
For instance,
struct student {
char names[50];
struct student point; /* The data type here will be invalid. */
int *f();
};
The example mentioned below, however, will be invalid in a program:
struct student {
char names[50];
struct student *point;/* The member can consist of a pointer to the student structure. */
int (*f)(); /* It is a pointer to a function that returns int */
};
There must be a unique name for a declared structure member within any structure. However, note
that we can use it in another unnested or even nested structure, or even namespaces for referring to a
different type of object.
For instance,

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
46
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

struct {
int a;
struct {
int a; /* The ‘a’ here would refer to a different object as compared to the previous ‘a’ */
};
};
A compiler would basically assign storage for all the structure members in the exact order of the
member declaration. It has an increasing memory address for all the members occurring subsequently.
Here, the very first member happens to begin at the structure’s starting address itself. Then the
alignment of the subsequent members occurs according to the alignment unit. Now, it may
differ on the basis of the sizes of the members present in the structure.
A typical structure may consist of unused bits (padding) so that all the members of an array of
all such structures are aligned properly. Thus, the size of a structure becomes equal to the total
storage necessary for all of its members in addition to any of the padded spaces required for meeting
the requirements of alignment.
Unions
The union is also a derived form of data type in the C language, which is quite similar to the structure.
But here, the amount of memory that it uses is actually equal to the size of that union member
contained in it, which takes up the maximum storage space.
The union type is responsible for storing objects of various different types in the very same location of
the memory. It means that in any program,
various different types of union members would
be able to occupy the very same location at
different times. A union declaration includes all
of the members present in a union. It lists all the
possible object types that a union is capable of
holding. A typical union is capable of holding
any one of the members at any given time. The
subsequent assignment of any other member to
the very same union would lead to the
overwriting of the existing object present in the
same specified storage area.
We can name the unions using any valid identifier. Keep in mind that we cannot declare an empty
union, and a union is incapable of containing an instance of itself. The union members can’t have a
function, the void, or even an incomplete type, but the unions can consist of pointers to the unions of
their own type.
In simpler terms, we can view unions as single objects that are capable of representing various objects
of different types in the same location at different times. A union would let anyone use those objects
whose size and type can easily change with the progress of the program – even if you don’t use some
machine-dependent type of constructions. This concept is also known as a variant record in some
other languages.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
47
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The syntax that we use to define the unions is similar to that of the syntax used for writing the
structures. Here, the definition of every union type would lead to the creation of a new type. We must
use unique names for all the union members, but these names can also be duplicated in various other
unnested or nested unions as well as namespaces.
For instance,
union {
int a;
union {
int a; /* The ‘a’ used here would refer to an entirely different object as compared to the previously
used ‘a’ */
};
};
Here, the size of any union would be equal to the total storage necessary for the largest member in the
union and also, any padding required for meeting the requirements of alignment.
For instance, if we have a union that consists of a float, an array of 5 char, and an array of 5 integers,
then the union storage space would be equal to a total of 20 bytes for a 64-bit compiler type.
Function
The function type is basically used to define a function that would return any value of specified
types. Whenever a function doesn’t return a value, it must be declared in the form of a function
returning void. We can do this as follows:
void function ();
The example mentioned below contains the data type for its functions as the function returning int.
Here is how the code will be:
int add()
{
int x=10, y=10, z;
z=x+y;
return z;
}
How do we calculate the size of any given function?
Here is how we calculate the size of any available function:
Size of a function = Total size of all the local variables that have been declared in the function + the
size of the global variables that have been used in the function + the size of all of the parameters + the
size of the returned value when it’s an address.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
48
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

For instance, here is how we calculate the size of any add function:
int add()
{
int x=10,y=10,z;
z=x+y;
return z;
}
Thus, the answer that we would get here is about 12 bytes for a 64-bit type of compiler.
Pointers
The pointers are also derived data types in the C language. The size that a pointer takes up in the
memory is always pretty much fixed. Still, the type of pointer that we get depends entirely on the type
of that element for which it stores the address.
Thus, it’s like if the pointer stores the address of
an available integer, then the pointer type would
be equal to the integer point. On the other hand, if
the pointer happens to store an array’s address,
then the pointer type would be equal to the array
pointer.
In simpler words, we can define pointers in C
language as the variables that are capable of storing the address of any other variable in them. The
pointers in C can also hold the address of any type stored in them, be it the FLOAT, INTEGER,
ARRAY, STRING, FUNCTION, and STRUCTURE.
Double data type in C :
The double data type in the C language is responsible for storing very large numeric values, which
the float (floating point) or integer data types aren’t able to store in any given program.
Why Do We Use Double Data Type in C?
The double data type or double refers to that data type in the C language that helps in storing high-
precision sorts of floating-point numbers or data in the computer memory. This data type is also
known as double because it is capable of holding double the size of info and data as compared to the
float.
Thus, a double consists of 8 bytes of data- which is equal to a total of about 64 bits of size. Here, the
double utilises 11 bits for its exponent, 1 bit for representing the sign, and all the rest of 52 bits for the
mantissa of the double. The double data type ranges from 1.7E-308 to 1.7E+308.
We can also represent the double data in the form of a real number (2, 20), minus (-2, -0.00001), and
decimals (0.2, 22.001).
Keep in mind that a double is capable of holding about 15 to 16 digits after and before any given
decimal point (approximately).
Example: 1.9876, 5.43219, -876.543, 21.987654, 0.15197e-7, etc.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
49
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Process of Declaration and Initialization of a Double Variable in the C language


Here is how we can declare and initialize any double variable in a given C program:
Declaration
We first need to specify the variable name along with the data type for performing the declaration of
the double variable in the C language.
Syntax,
double info1;
Initialization
For performing the initialization of a double variable, we need to specify any value to the variable
name. This value must be valid.
Syntax,
info1 = 3.2325467;
Added to this, one can also declare the variable along with initializing it in the very same line.
Syntax,
double info1 = 3.2325467;
Examples
Let us take a look at an example where we declare and initialize the perimeter in a program.
Declaration
double perimeter1;
Initialization
perimeter1 = 40000;
Declaration and Initialization in a Single Line
double perimeter1 = 40000;
Program for Converting Centimeters into Inches with the Use of Double Data Type in C
Let us take a look at an example where we pass the available number for the double data type to a
function for converting feet into meters in a program.
#include <stdio.h>
double centimeter_to_inch (double f); // declaration of a user defined type of function
int main()
{
double centimeter, cnvt; // declaration of the intended variable in the form of a double data type
printf (” We will enter the centimeter in double “);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
50
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

scanf(“%lf”, &centimeter);
cnvt = centimeter_to_inch (centimeter); // calling of the centimeter_to_inch function in program
printf (” The answer for converting centimeters to inches is: %lf”, cnvt);
return 0;
}
// performing the definition of the given function
double centimeter_to_inch (double f)
{
return f / 2.54;
}
The output obtained out of the program mentioned above will be:
We will enter the centimeter in double 45.78
The answer for converting centimeters to inches is: 18.023622

Program for Converting Integer Data Type into Double Data Type in C
Let us take a look at an example where we convert an int number in the C language into a double data
type number.
#include <stdio.h>
int main()
{
int num = 68, denom = 22;
double val;

val = (double) num /


denom;
printf (” The
conversion of an int value in C into a double data type will generate an output of : %lf \n”, val);
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
51
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The output obtained out of the program mentioned above will be:
The conversion of an int value in C into a double data type will generate an output of :
3.09090909091

Program for Converting Fahrenheit Temperature into Celsius Temperature with the Use of
Double Data Type in C
Let us take a look at an example where we perform the conversion of a temperature given in
Fahrenheit to Celsius in a C program.
#include <stdio.h>
int main()
{
// the declaration of the given double variable
double f_temp, c_temp;
printf(” Please enter your temperature in Fahrenheit: “);
scanf (” %lf”, &f_temp); // accepting of the Fahrenheit
temperature
c_temp = ( f_temp – 1.8 ) * 5 / 9; // using the conversion formula
here
printf (” Your temperature in Celsius is: %lf”, c_temp);
return 0;
}
The output obtained out of the program mentioned above will be:
Please enter your temperature in Fahrenheit: 56.8
Your temperature in Celsius is: 13.77778
Program for Printing the Sum of Two of the Double Numbers
with the Use of Function in C
Let us take a look at an example where we perform the sum of
two double numbers in a C program with the use of a function.
#include <stdio.h>
double add_val(double a, double b);
int main()
{
// the declaration of given double variables in the program
double p, q, res;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
52
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

printf (” Please enter two of your double numbers here “);


scanf(” %lf %lf”, &p, &q); // the program takes two double variables from its user
res = add_val(p, q); // the calling of the double function
printf (” We have found the result of the two double numbers in the program to be: %lf”, res);
return 0;
}
double sum_num(double a, double b)
{
return a + b; // the returning of the sum of the given double values in the program
}
The output obtained out of the program mentioned above will be:
Please enter two of your double numbers here 34.568
43.797
We have found the result of the two double numbers in the program to be: 78.365000
Float Data Type vs. Double Data Type: A Comparison
While some might confuse both of these data types while programming in C, there is a significant
difference present between them. Let us discuss that in brief.
Float
The float data type is basically a single-precision sort of data type that is capable of holding 32
bits of decimal numbers or floating points. It equals a total of 4 bytes, and it is predefined in
nature. It means that the float is a type of keyword whose name and meaning cannot be
changed by a programmer throughout the program.
As a matter of fact, the float data type is much faster as compared to the double data type. It is mainly
because of its small range in a program. It is capable of holding about 7 digits approximately. Also,
keep in mind that a float data type basically ranges from 1.5 x 10-45 to 3.4 x 1038.
Double
The double data type is basically a precision sort of data type that is capable of holding 64 bits of
decimal numbers or floating points. Thus, it is capable of storing exactly the double size of data,
compared to the float data type. The double is also a predefined data type. It means that we cannot
change its name and meaning throughout the program when it is running. But keep in mind that
because it holds larger values, it is much slower than that of the float data type. It is very big in size,
thus very slow, and it can easily accommodate about 15 to 17 digits after or before a decimal point.
The typical range of a double is about 5.0 x 10-345 to 1.7 x 10308.

Enumerated data type in C

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
53
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The enumerated data type is also known as the enum in the C language. Now, enum is not a basic, but
a user-defined form of data type that consists of various integer values, and it functions to provide
these values with meaningful names. Using the enum data type in C language makes any program
much easier to maintain as well as understand. We define enums using the keyword “enum”.
Definition of Enumerated Data Type in C
Here is how we can define an enum in C language:
enum flag{integer_constant1, integer_constant2,…..integter_constantN};
As you can see in the declaration mentioned above, one would define an enum to be named as a flag
that contains about ‘N’ numbers of integer constants. Here, the default value of any integer_constant1
would be equal to 0. Then the value of integer_constant2 would be 1, for integer_constant3 it would
be 2, and so on. However, it is just the default value and we can change it when declaring an enum.
Let us take a look at an example:
enum week{Mon, Tue, Wed, Thurs, Fri, Sat, Sun};
Here, the default value assigned to Mon is 0, Tue is 1, Wed is 2, Thurs is 3, Fri is 4, Sat is 5, and
Sun is 6. In case we want to change all of their default values, then here is what we should do:
enum week{
Mon=13,
Tue=27,
Wed=45,
Thurs=86,
Fri=921,
Sat=364,
Sun=578,
};

Declaration of Enumerated Data Type in C


As we all know, we must declare any variable in the C language, which is basically of a pre-defined
type, like char, float, int, etc. In a similar manner, we can also declare the variables present in the user-
defined data types like the enum data type. Now, here is how one can declare any variable present in
an enum data type.
Let us assume that we are creating an enum of true and false status. It will appear as follows:
enum status{true,false};
Now, here is how we create a variable for the status enum type:
enum status x; // creation of a variable that belongs to the status type.
In the case of the statement mentioned above, we have performed the declaration of the variable ‘x’ of
the type status. Thus, if we want to create variables, then we can write the two statements mentioned
above as:

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
54
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

enum status{true,false} x;
Here, the default value for true would be equal to 1, while for false, it will be equal to 0.
Why use an enum in a program?
One can utilise the enums in a program when they want the variables in the program to have just the
set of values. For instance, let us consider the creation of a direction variable. Now, there are a total of
four directions (N, S, W, E). Thus, a total of four values are possible with the direction variable. But
here, the variable would be able to hold just a single value at any given time. Now, if a user provides
any different value to the variable here, then we would get a compilation error.
We can also use the enum in the case of switch case statements. In this statement, we pass all the
enum variables within the switch parenthesis. This step would basically ensure that we have to
define the value of the case block in an enum.
Now, we will see how one can make use of an enum within a switch case statement. Let us take a
look:
#include <stdio.h>
enum vegetables{broccoli=1, spinach, carrot, eggplant, celery, pumpkin, shallot};
int main()
{
enum vegetables v;
v=broccoli;
switch(v)
{
case broccoli:
printf(“I will eat broccoli”);
break;
case spinach:
printf(“I will eat spinach”);
break;
case carrot:
printf(“I will eat carrot”);
break;
case eggplant:
printf(“I will eat eggplant”);
break;
case celery:

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
55
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

printf(“I will eat celery”);


break;
case pumpkin:
printf(“I will eat pumpkin”);
break;
case shallot:
printf(“I will eat shallot”);
break;
}
return 0;
}
The output generated here would be:
I will eat broccoli
Important points to remember about enum
 The names of enums available in any enum type are capable of having the very same
value. Take a look at the following example to understand this better.
#include <stdio.h>
int main(void) {
enum cosmetics{lipstick= 1, blush=0, mascara=1};
printf(“The given value of lipstick is %d”, lipstick);
printf(“\nThe given value of mascara is %d”, mascara);
return 0;
}
The output generated here would be:
The given value of lipstick is 1
The given value of mascara is 1
 In case we fail to provide any values to these enum names, the compiler would then assign
these enums with a default value, starting from 0 (for the first one).
 A programmer can provide any values to the enum names in any order they like.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
56
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 All the unassigned enum names would be assigned with a default value automatically, which
would be equal to the value of the previous enum plus one.
 Any value that we assign to these enum names must be in the form of integral
constants. It means that it must not be of any other type, like float, string, etc.
 All of the enum names must have a very unique scope of their own. In simpler words,
whenever we define two separate enums with the very same scope, then it is necessary that
these two enums have separate enum names. If it doesn’t happen, then the compiler would
throw a compile-time error.
 We can also define any enumerated data type in an enumeration without its name.

Size of data types in c


Data types are one of the most crucial features in the C programming language. We use the data types
with functions and variables for defining what kind of data it typically holds. This data can be some
type of character or value. There can also be various sets of characters or sets of values. The C
language offers a very wide range of all the data types, and each of these may contain a unique data
type with some certain range that is predefined.
Types of Data Types in C
The C programming language has two basic data types:
 Primary
 Derived
Primary Data Types
The primary data types are basically standard data types that the C language defines. The language
defines four of the basic data types in programming. These are:
char – these are single-byte in nature. The char data type can hold a single character in a local
character set.
float – these are single-precision types of floating-point.
int – these are integers. They typically reflect the integer’s natural size on a host machine.
double – these are double-precision types of floating-point.
Apart from this, one can also apply various numbers of qualifiers to the basic data types. The long and
short qualifiers applied to integers would turn out to be:
long int counter;
short int sh;
*Note that we can omit the word int in such types of declarations.
Size of Primary Data Types
Here is a list of all the primary data types:

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
57
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Type Range Size (in bytes)

unsigned char 0 to 255 1

signed char or char -128 to +127 1

unsigned int 0 to 65535 2

signed int or int -32,768 to +32767 2

unsigned short int 0 to 65535 2

signed short int or short int -32,768 to +32767 2

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

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

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

double 1.7E-308 to 1.7E+308 8

float 3.4E-38 to 3.4E+38 4

The data type size and range depend a lot on the compiler. However, the code that the compiler
compiles is targeted for some specific types of Microcontrollers or Microprocessors. One single
compiler can provide support for multiple targets or processors. The compiler then defines the size for
the available data types on the basis of the selected target. In simpler words, the size of any data
type is directly dependent on the compiler along with the target processor (for which the code
generation occurs using the compiler).

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
58
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

In the table mentioned above, we have assumed a 16-bit compiler. It means that the code generation of
the compiler will be for a 16-bit target processor. The integer is, normally, the natural size for any
processor or machine. In the table mentioned above, the integer is 16-bit or 2 bytes wide. Thus, the
compiler is also 16-bit or 2 bytes wide. If the compiler was 32-bit wide, the int type size would have
been about 32-bits or 4 bytes. However, this might not be the case every single time. It is also possible
that the integer size is 32-bits or 4 bytes for a 64-bits processor. It entirely depends on the type of
compiler.
Let us take a look at an example of an integer data type:
int temp; // the ‘temp’ variable is capable of holding the integer values
(both negative or positive)
temp = 50;
temp = -50;
signed int temp; // the ‘temp’ variable is capable of holding the integer values
(both negative or positive)
temp = 987654;
temp = -987654;
unsigned int temp; // the ‘temp’ variable is capable of holding the integer values
(only positive)
temp = 87654;
temp = -8; // The given assignment is invalid
Char Size
The size of both unsigned and signed char is 1 byte always, irrespective of what compiler we use.
Here, a signed character is capable of holding negative values. Thus, the defined range here is -128 to
+127. But the unsigned character is only capable of holding the positive values. Thus, the range for
such characters is from 0 to 255. These character data types are capable of storing the ASCII
characters or the numbers that are equivalent to the ASCII characters.
Short Integer Size
The size of both unsigned and signed integers is about 2 bytes in a majority of the compilers.
Long Integer Size
The size of both unsigned and signed long integers depends on the type of compiler that we use. The
size is typically about 32-bits or 4 bytes on a 16/ 32-bit compiler. Yet, it varies depending on what
compiler we are using.
There is no specification of the data types sizes according to the C standard, except the character.
According to the definition by C:
Every compiler can choose an appropriate size for hardware of its own. It is only subjected to a
single restriction that the longs are 32 bits at least, ints and shorts are 16 bits at least, the short is
not longer than the int, and the int is not longer than the long.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
59
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

What differentiates the range for unsigned and signed types?


Although the size of any unsigned as well as the signed data type is all the same, they both possess
different ranges of values to be stored in any variable. Why? It is because the representation of the
signed numbers is in 2’s complement form in any processor or machine. For instance, the
representation of the number -23 in the form of 2’s complement would be:
(Decimal) 23 <-> (Binary) 10111
The 1’s complement
The 1’s complement of 10111 will be –
1111111111111111111111111111111111111111111111111111111111101000
Here, the total number of 1s that are added before the actual number depends a lot on the size of the
machine or that of the target processor. Since the machine we are dealing with here is a 64-bit
machine, we have added these many 1s, so that the final number also becomes a 64-bit number.
In simpler words, the 1’s complement is basically an inverted version of the actual number. The
0s get converted to 1s and the 1s get converted to 0s.

The 2’s complement


The 2’s complement is basically 1’s complement + 1, i.e.,
1111111111111111111111111111111111111111111111111111111111101000 + 1:
1111111111111111111111111111111111111111111111111111111111101001 <-> (decimal) -23
Some calculations on the computer would help you verify this result here.
Let us take a look at an example of a signed character that is capable of storing numbers that fall
between -128 to +127. Now, we all know that both unsigned and signed char are capable of storing
just 8-bits of data in them.
So, if we assume that we are trying to store a number, -190, in an 8-bits wide variable character, then
the processor would handle the number as follows:
(Decimal) 190 <-> (Binary) 10111110 : 8-bits
1’s complement of the value 190: (Binary) 01000001 : 8-bits
2’s complement of the value 190: (Binary) 01000010 : 8-bits
(Binary) 01000010 <-> (Decimal) 66
The interpretation of the character numbers by the computer would be as follows:
(1) MSB bit: The sign of the number [0: Positive, 1: Negative], 7-0 Bits: 1000010: [66] Actual data
It means that whenever we try to store a number that is greater than the defined range, the number will
ultimately get rounded down. Thus, we got the result of 256-190 to be 66. Here, 256 is basically the
maximum value that an unsigned character number can keep stored.
Now, let us take a look at another example of how we can store the number -126 in a variable of char
data type.
(Decimal) 126 <-> (Binary) 01111110

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
60
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

1’s complement of 126: (Binary) 10000001 : 8-bits


2’s complement of 126: (Binary) 10000010 : 8-bits
(Binary) 10000010 <-> (Decimal) -126
If you want to verify the obtained results, you can perform reverse calculations. Here, the number
is negative since the MSB is 1. Also, 0000010 are the other 7 bits. Thus, the number’s 2’s
complement would be: ~0000010 = 1111101 = (Decimal) 126
If we combine the number and the sign here, we will obtain the result to be: (Decimal) -126
The very same concept goes well with both unsigned as well as signed integer data types.
In a brief conclusion, both unsigned and signed numbers have the very same definition for data size in
C. However, the representation of the signed numbers is in the 2’s complement form, and the binary
number’s most significant bit represents that number’s sign. Since binary 1 (extra 1 bit) is there to
identify this given number as negative, the overall range of the signed numbers is much less than that
of the unsigned numbers.
Your processor handles the negative numbers, and thus, you don’t have to take care of them
separately. Just make sure that you assign a valid number to the signed variable that falls in the
defined range. In case you fail to do this, the assigned number will ultimately get truncated.

The Floating Point Data Types


The C language specifies two of the primary data types for storing the fractional numbers or the
floating-point. These are double or float. One can easily apply the long qualifiers on the double.
Thus, we get another type, which is the long double.
In a computer system, the IEEE-754 format represents the floating-point numbers. A majority of
modern processors and processors adopt this format. It has two major representations:
1. 32-bit single precision
2. 64-bit double precision
The representation of the floating numbers has further classifications. These are:
1. The Normalised Form
We will take a look at an example to understand this better.
Assume that the 32-bit type of pattern is
1 1000 0001 011 0000 0000 0000 0000 0000, where:
F = 011 0000 0000 0000 0000 0000
E = 1000 0001
S=1
In a normalised form, the mantissa or the actual fraction is normalised using an implicit that
leads 1, which is in the form of 1.F. For instance, in the example mentioned here, the actual
fraction would be 1.011 0000 0000 0000 0000 0000 = 1 + 1×2^-2 + 1×2^-3 = 1.375D.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
61
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Here, the sign bit basically represents the number’s sign, where S=1 is a negative number and S=0 is a
positive number. In the example mentioned above, the S=1. Thus, the number is negative. It means
that the number would be -1.375D.
The actual exponent in the normalised form would be E-127 (it is the so-called bias-127 or excess-
127). It is because a person needs to represent both negative and positive exponents. In the case of an
8-bit E that ranges from 0 to 255, the actual exponent of the numbers -127 to 128 could be provided
by the excess -127 scheme. For instance, in the mentioned example, E-127=129-127=2D.
2. The De-Normalised Form
The normalised form has some serious problems. For instance, it uses an implicit that leads 1 for a
fraction. Thus, the normalised form cannot represent zero as a number that would start with 1. The de-
normalised form is basically devised for representing the number zero as well as the other numbers.
These numbers are in a de-normalised form for the E=0. An implicit that leads 0 and not 1 would be
used for a fraction. The actual exponent here is always -126. Thus, we can represent the number 0
using an F=0 and an E=0, because 0.0×2^-126 = 0.
A person can easily represent very small negative and positive numbers in a de-normalised form using
an E=0. For instance, if F=011 0000 0000 0000 0000 0000, E=0, and S=1, the actual fraction would
be 0.011 = 1×2^-2+1×2^-3 = 0.375D. Now since S=1, the given number is actually negative. Now
with E=0, -126 would be the actual exponent. Thus, the number here is -0.375 × 2^ – 126 = -4.4×10^
– 39. Now, this is an extremely small number that is negative (very close to the number 0).
Summary:
The calculation of the value N would be:
(a) For 1 ≤ E ≤ 254, N = (-1)^S × 1.F × 2^(E-127).
The numbers here are in a normalised form. The sign of the number here is represented by the sign-
bit. The implicit that leads 1 normalises the fractional part, that is 1.F. The exponent here is in excess
(or bias) of 127 for representing both negative and positive exponents. The overall range of the
exponents here would be -126 to +127.
(b) In the case of E = 0, N = (-1)^S × 0.F × 2^(-126).
All of these numbers are in the de-normalised form. Thus, the exponent of the value 2^-126 would
then evaluate as a number that is very small. We need to represent the denormalised form using
E=0 and F=0. These can also represent extremely negative and positive numbers that are close to
the value of zero.
(c) In the case of E = 255, some special values would be represented, for instance, NaN (it refers to
not a number) and ±INF (the negative and positive infinity).
The Derived Data Types
These are also known as user-defined types. This data type is derived out of the primary data type,
thus known as the derived data types. But these are capable of storing a set of various values instead
of storing one single value. Unions, structures, arrays, and enum are some of the most common ones
in the C language.
User defined data types in c

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
62
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The UDT (User-Defined Data Type) is a typical data type that we can derive out of any existing data
type in a program. We can utilise them for extending those built-in types that are already available in a
program, and then you can create various customized data types of your own.
Why do we Need User-Defined Data Types in C?
The data types originally present in a program may not offer a wide variety of functions. But
despite the various basic as well as derived data types present in the C language, there is a special
feature using which we can define custom data types of our own, on the basis of our needs. The
User-Defined Data Types are basically defined by a user according to their will. These offer various
functions on the basis of how one defines them. Thus, these are termed to be “User-Defined”.
Example
Let us take a look at an example where we define a structure in a C program.
struct student
{
char name[100];
int roll;
float marks;
}
In this case, we have created a structure that will further allow us to create a data type of our own.
Here’s how we can do it:
struct student info;
In this case, the UDT is a “student”. Here, the info is a variable that will hold the roll number,
marks, and name of the student.
Types of User-Defined Data Types in C
The C language allows a feature known as the type definition. This basically allows a programmer to
provide a definition to an identifier that will represent a data type which already exists in a program.
The C program consists of the following types of UDT:
 Structures
 Union
 Typedef
 enum
Structures
We use the structure for organising a group of various data items into one single entity – for grouping
those data items that are related but might belong to different data types.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
63
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The structure data types are related (usually), such as the different sets of information regarding a
person, an account, or a part, etc. Every data item present in a structure is known as a member. These
members are sometimes also known as fields.
We use the struct keyword for creating a structure. The primary advantage of using a structure is that
it becomes very easy for a person to access the members. It is because the allocation of all the
members that belong to a specific structure is in the continuous memory. Thus, structure helps in
minimising the memory access time for any program.
Generally, we declare a structure as follows:
struct name_of_tag {
data_typea svar_a;
data_typeb svar_b;
data_typec svar_c;
….
….
data_typez svar_z;
};
The beginning of the declaration of a structure typically begins with the struct keyword. We must
enclose the declaration of all the members of the structure in braces. Here, the tag_name refers to the
identifier that would specify the name of the new structure.
The structure declaration reserves no storage space – but the structure definition would lead to the
creation of the structure variables.
We can define the structure variables as follows:
struct tag_name svar_a, svar_b …svar_z;
An example would help us understand this better:
struct sample {
int p, q;
float r, s;
char t, u;
};
struct sample vA, vB, vC; //definition of structure
Union
A union is basically a collection of various different data types that are present in the C language, but
not very similar to each other. The union mainly allows the storage of those data types that are
different from each other in the very same memory location.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
64
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Any user will be able to define a union using various members, but at any given time, just a single
member would be able to contain the given value. The unions provide us with an efficient way in
which we can use the very same memory location for multiple purposes.
Note that the structures and unions are very similar to each other. The only difference between them is
that we can access just a single member of the Union at any given time. It is because the creation of
memory is only for one member that has the biggest size (or the highest number of bytes).
We declare the union using the union keyword, and we can access all the members of a Union
using the (.) dot operator.
The definition and declaration of a union would go like this:
union tag_name {
data_typea uvar_a;
data_typeb uvar_b;
……
data_typez uvar_z;
};
union tag_name uvar_a, uvar_b,….uvar_z;
We will understand this better with the help of an example,
union sample {
int duration;
float cost;
char keyword;
};
union sample x;
In the example mentioned above, the allocation of about 4 bytes of memory occurs to the union
variable x. Thus, we can access the members as x.duration, x.cost, x.keyword, etc., but we can only
access one of the members at any given time since the very same memory exists for all three members
here.
Typedef
We use the keyword typedef for creating an alias (a new name) for a data type that already exists. The
typedef won’t create any new form of data type.
When using the typedef data type, the syntax would be:
typedef existing_data_type new_type;
Let us consider the example as follows:
#include <stdio.h>

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
65
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

void main() {
typedef int Lessons; //statement-1
Lessons x = 17;
printf(“Given value =%d\n”, x);
}
Let us look at the statement here. We have used the typedef statement for creating Lessons as
an alias for int. After we use this statement, Lessons will become the new name for the int data type in
the program given above. Also, the variables that are declared in the form of Lessons data type will
behave like the int variables in all the practical implications of the program.
enum
The enum refers to a keyword that we use for creating an enumerated data type. The enum is basically
a special data type (enumerated data type) that consists of a set of various named values – known as
members or elements. We mainly use it for assigning different names to the integral constants. This
way, the program becomes much more readable.
Here is the format that we use for creating the enum type:
enum identifier (value_a, value_b, …. , value_z);
The enumerated data types basically allow a user to create symbolic names of their own for a list of
all the constants that are related to each other.
For instance, you can create the enumerated data type for the true and false conditions this way:
enum Boolean {
true,
false
};
In case we don’t assign values explicitly to the enum names; the compiler, by default, would assign
the values that start from 0.
In this case, true and false would be automatically assigned to 1 and 0 respectively. In simpler words,
the first field of the enum value here will be replaced by 1, and then the next field will be replaced
with 0, and so on.
Let us take a look at an example to display how to use the enum data value.
#include <stdio.h>
void main() {
enum week {MON = 1, TUE, WED, THURS, FRI, SAT, SUN};
enum week off = FRI;
printf(“Week Off = %d”, birthday);
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
66
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Here, the field name MON will be assigned with the value 1. Thus, the next field name TUE will be
assigned with the value 2 automatically, and so on.
The program mentioned above will print the following output:
Week Off = 5

Operators in c
The operators are types of symbols that inform a compiler for performing some specific logical or
mathematical functions. The operators serve as the foundations of the programming languages. Thus,
the overall functionalities of the C programming language remain incomplete if we do not use
operators. In simpler words, the operators are symbols that help users perform specific operations and
computations- both logical and mathematical on the operands. Thus, the operators operate on the
available operands in a program.

Use of Operators in C
The operators basically serve as symbols that operate on any value or variable. We use it for
performing various operations- such as logical, arithmetic, relational, and many more. A programmer
must use various operators for performing certain types of mathematical operations. Thus, the primary
purpose of the operators is to perform various logical and mathematical calculations.
The programming languages like C come with some built-in functions that are rich in nature. The use
of these operators is vast. These operators act as very powerful and useful features of all the
programming languages, and the functionality of these languages is pretty much useless without these.
These make it very easy for programmers to write the code very easily and efficiently.
Types of Operators in C
Various types of operators are available in the C language that helps a programmer in performing
different types of operations. We can handle different operations in a program using these types
of operators:
 Relational Operators
 Arithmetic Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Misc Operators
Relational Operators

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
67
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

We use the relational operators in c when we would like to compare the values available for two given
operands. Here is a table that states all the relational operators available in the C language, along with
their individual functions.

Function of Operator Operator Example

To check if two operands are equal to each other. == 5 == 3 would return


to 0
and 4 == 4 would
return to 1

To check if two operands are unequal to each other. != 8 != 5 would return to


1
6 != 6 would return to
0

To check if the operand value on the left is comparatively greater than > 5 > 8 would return to
that of the operand value on the right. 0
9 > 7 would return to
1

To check if the operand value on the left is comparatively smaller than < 2 < 0 would return to
that of the operand value on the right. 0
4 < 8 would return to
1

To check if the operand value on the left is equal to or comparatively >= 1 >= 5 would return
greater than that of the operand value on the right. to be 0
4 >= 2 would return
to be 1

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
68
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

9 >= 9 would return


to be 1

To check if the operand value on the left is equal to or comparatively 3 <= 6 would return
smaller than that of the operand value on the right. to be 1
7 <= 3 would return
to be 0
2 <= 2 would return
to be 1

Note – Here, we get 1 as output when the condition is true, and 0 as output when the condition is
false.

Arithmetic Operators
The arithmetic operators in C language help a user perform the mathematical operations as well as the
arithmetic operations in a program, such as subtraction (-), addition (+), division (/), multiplication
(*), the remainder of division (%), decrement (–), increment (++).
The arithmetic operators are of two major types:
 Binary Operators – It works using two of the operators, such as -, +, /, *.
 Unary Operators In C – It works by making use of just a single operand (value), such as —
and ++.
 Also, Explore Ternary Operator in C.
Binary Operators
Here is a table that states all the binary arithmetic operators available in the C language, along with
their individual functions. If P = 50 and Q = 25, then:

Function of Operator Operator Example

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
69
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

To subtract the value of the second operator from the first one. – P – Q = 25

To add the value of the second operator with the first one. + P + Q = 75

To divide the value of the numerator with the value of the denominator. / P/Q=2

To multiply the value of the second operator with the first one. * P * Q = 1250

Unary Operators
Here is a table that states all the unary arithmetic operators available in the C language, along with
their individual functions. These are increment and decrement operators. If P = 50 and Q = 25, then:

Function of Operator Operator Example

To increase the value of the integer/ operator by 1. Decrement Operator P — = 49


and Q — = 24

To decrease the value of the integer/ operator by 1. Increment Operator P ++ = 51


and Q ++ = 26

Prefix and Postfix Increment/ Decrement Operators


The decrement operators and increment operators are of two major types:
Prefix – When we use the operator before the available variable in a program as a prefix, it is
known as a prefix operator. In a prefix increment operator, the program first adds 1 and then
assigns the resultant value to the variable. While in a prefix decrement operator, the program
first subtracts 1 and then assigns the resultant value to the variable. For example, ++a and –a.
Postfix – When we use the operator after the available variable in a program as a postfix, it is known
as a postfix operator. In a postfix increment operator, the program first assigns the value to the
variable, then adds 1, and then assigns the resultant value. While in a postfix decrement operator, the
program first assigns the value to the variable, then subtracts 1, and then assigns the resultant value.
For example, a++ and a–.
Here is a table that states all the prefix and postfix unary arithmetic operators available in the C
language, along with their individual functions. These are increment and decrement operators.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
70
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Type of Operator Sample Operator Description/ Explanation


Expression

Prefix Increment ++p p increases by a value of 1, then the program uses the
Operator value of p.

Postfix Increment p++ The program uses the current value of p and increases
Operator the value of p by 1.

Prefix Decrement –p p decreases by a value of 1, then the program uses the


Operator value of p.

Postfix Decrement p– The program uses the current value of p and decreases
Operator the value of p by 1.

Logical Operators
The logical operators in c help a user determine if the results would be true or false. Here is a table
that states all the logical operators available in the C language, along with their individual functions.
If P = 1 and Q = 0, then:

Name of Operator Description of Operator Example


Operator

Logical ! We use this operator for reversing the available logical state !(P && Q) turns
NOT of the operand. In case the condition turns out to be true, out to be true.
then this operator will make the value false.

Logical OR || The given condition turns out to be true if any of the (P || Q) turns out
operands happen to be non-zero. to be true.

Logical && The given condition turns out to be true if only both the (P && Q) turns
AND operands happen to be non-zero. out to be false.

Assignment Operators
We use the assignment operators in c for assigning any value to the given variable. Here is a table that
states all the logical operators available in the C language, along with their individual functions.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
71
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Function of Operator Operator Example

To assign the values from the right operand to the left operand. = p=q

To add the value of the right operand with the value of the left += p += q is similar to that
operand. After that, assign the resultant value to the left one. of p = p=q

To subtract the value of the right operand from the value of the left -= p -= q is similar to that
operand. After that, assign the resultant value to the left one. of p = p-q

To multiply the value of the right operand with the value of the left *= p *= q is similar to that
operand. After that, assign the resultant value to the left one. of p = p*q

To divide the value of the right operand with the value of the left /= p /= q is similar to that
operand. After that, assign the resultant value to the left one. of p = p/q

To calculate the modulus of the values of the right operand and the %= p %= q is similar to that
left operand. After that, assign the resultant value to the left one. of p = p%q

Bitwise Operators
We use bitwise operators in c for performing the operations of bit-level on various operands. It first
converts the operators to bit-level, and after that, it performs various calculations.
The Bitwise operators basically work on the bits, and we perform bit-by-bit operations using them.
Here is the truth table for the ^, &, and | here:

a b a&b a|b a^b

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
72
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

1 1 1 1 0

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

If we assume that P = 60 and Q = 13 using the binary format, then it will appear as follows:
P = 0011 1100
Q = 0000 1101
—————–
P ^ Q = 0011 0001
P | Q = 0011 1101
P & Q = 0000 1100
~ P = 1100 0011
Here is a table that states all the bitwise operators available in the C language, along with their
individual functions. If we assume that the value of variable P = 60 and variable Q = 13, then:

Name of Description of Operator Example


Operator Operator

Binary AND & This operator copies the bits to the result only (P & Q) = 12,
if they exist in both of the operands.
The binary value is
0000 1100

Binary OR | This operator copies the bits only if they exist (P | Q) = 61,
in either of the operands.
The binary value is
0011 1101

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
73
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Binary XOR ^ This operator copies the bits only if they are (P ^ Q) = 49,
set in one of the operands but not in both of
them.
The binary value is
0011 0001

Binary One’s ~ This operator is unary. Also, it performs the (~P ) = ~(60),
Complement effect of ‘flipping’ the available bits.
The binary value is
-0111101

Binary Left Shift << It shifts the value of the left operand to the P << 2 = 240,
left on the basis of the number of bits that the
The binary value is
right operand specifies.
1111 0000

Binary Right >> It shifts the value of the left operand to the P >> 2 = 15,
Shift right on the basis of the number of bits that
the right operand specifies. The binary value is
0000 1111

Misc Operators
Apart from all the operators that we have discussed above, the C programming language uses a few
other crucial operators, that include operators, (such as ? : and sizeof). Here is a table that states all the
misc operators available in the C language, along with their individual functions.

Description of Operator Operator Example

To return the actual size of any given Size of() If z is an integer, then the size of(z) will return to be 4.
variable.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
74
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

To return the address of any given & For instance, &z; would return the actual address for
variable. any given variable.

Pointer to any variable. * *z;

Conditional Expression. ?: When the Condition is true ? then the value X :


In any other case, the value Y

Precedence of Operators in C
The precedence of the operators in C language helps in determining the preference in which the
operators must be evaluated in a program. Some operators display higher precedence as compared to
the others in the program. For instance, the precedence of the multiplication operator here is much
higher than that of the addition operator. Explore, Operator Precedence and Associativity in C to know
more.
Let us consider an example where a = 5 + 2 * 7; so here, the variable a gets assigned with the value 19
and not 70. It is because the precedence of the multiplication operator (*) is higher than that of the
addition operator (+). Thus, the program would first multiply 2 with 7, produce 14, and then add it
with 5 to get 19 as the final result.
The table below displays the operators according to their precedence. The ones with higher
precedence appear at the very top, and the ones with lower precedence appear at the very
bottom. In any given expression, the evaluation of the operators with higher precedence occurs
first.

Type of Operator Associativity Category

() [] -> . ++ – – Left to right Postfix

– + ! ~ – – ++ (type)* & sizeof Right to left The Unary Operator

/*% Left to right The Multiplicative Operator

–+ Left to right The Additive Operator

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
75
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

>> << Left to right The Shift Operator

< > >= <= Left to right The Relational Operator

!= == Left to right The Equality Operator

& 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

?: Right to left Conditional

= -= += /= *= %=>>= &= <<= |= ^= Right to left Assignment

, Left to right Comma

Arithmetic Operators in C

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
76
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

When programming in the C language, the arithmetic operators help in performing mathematical
functions. Arithmetic Operators in C allows a user to construct various formulas and mathematical
equations.
Types of Arithmetic Operators in C:
These are two types of Arithmetic Operators in C.
 Binary
 Unary
Binary Arithmetic Operators
This type of operator operates on two of the operands. A typical binary operator appears in this format
with its operands:
operand1 operator operand2
Let us assume that variable A has a value of 5, and variable B has a value of 10. Then:

Operator Description Example

– Subtraction of the second variable from the first one var = A – B = -5

+ Addition of two operands var = A + B = 15

/ Division of the numerator by the de-numerator var = B / A = 2

* Multiplication of both the operands var = A * B = 50

% The modulus operator and the remainder after the division of an integer var = B % A = 0

Unary Arithmetic Operators


This type of operator operates only on one operand. A typical unary operator appears in the following
format with its operand:
operator operand

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
77
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Let us assume that variable A has a value of 5, and variable B has a value of 10. Then:

Operator Description Example

— Decrease of the integer value by the decrement operator by one var = A–

++ Increase of the integer value by the increment operator by one var = A++

– Unary minus var = -A

+ Unary plus var = +A

Arithmetic Operators in Action


How to Perform Increment and Decrement in the C Programming Language
Here is a trick for such kinds of loops in your code: the decrement and increment operators. They are
very useful in such cases.
We use the ++ for adding one to a value of a variable, like:
var++;
Once we execute this statement, the overall value of a var variable increases by 1 (increment). It’s
similar to writing the code as following:
var = var + 1;
The decrementing operator — is the opposite of the ++ operator. Instead of a plus, here we have
two minus signs. The decrement operator decreases the value of the available variable by one.
For instance:
var–;
Once we execute this statement, the overall value of a var variable decreases by 1 (decrement). It’s
similar to writing the code as following: var = var – 1;
One can find the ++ used a lot, especially in the loops, for instance:
for(x=0;x<100;x++)
The looping statement mentioned above gets repeated about 100 times. And it is way too cleaner than
a user writing its alternative:
for(x=0;x<100;x=x+1)
How does one Prefix the — and ++ Operators?

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
78
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

The operator — always decrements the available value of the variable, while the ++ increments the
value. Knowing this, we can consider the following statement:
var = A = B++;
In this case, if the value of the available variable is 17, then you must know that it will be 18 after
we perform the ++ operation. So, what is the original value of the variable now- 17 or 18?
Generally speaking, we read the math equations of the C language from left to right. On the basis
of this rule, the value of the variable preceding the execution of the statement is 17, and the current
value of the variable is 18.
What comes first in operation — the = or the ++?
When we place the — or the ++ operator after a given variable, then it is known as post-decrementing
and post-incrementing, respectively. In case we want to decrement or increment the given value of the
variable before we use it, then we place the — or ++ before we place the name of the variable. For
instance:
a = ++b;
Here, we can witness that there is an increment in the value of b, and then it gets assigned to the
variable a.
Also, what if a complex condition occurs, such as:
a = ++b++;
We would get no output. It is because the ++var++ results in an error in the code. So we can ignore
this condition.
How can one Discover the (Modulus) Remainder?
Out of all the basic symbols of the arithmetic operator, the % is the strangest. It is not an operator for
the percentage- it is, rather, a modulus operator. This modulus operator calculates the remainder
obtained by one number divided by the other.
Any modulus operation will display the remainder of the first value that gets divided by the
second value. Thus, 21%5 will be 1, but 20% of 5 will be 0.
Examples of Arithmetic Operators
Go through the following example to understand how all the arithmetic operators function in the C
program:
#include <stdio.h>
main() {
int p = 21;
int q = 10;
int r ;
r = p + q;
printf(“Line 1 – Value of r is %d\n”, r );

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
79
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

r = p – q;
printf(“Line 1 – Value of r is %d\n”, r );
r = p * q;
printf(“Line 1 – Value of r is %d\n”, r );
r = p / q;
printf(“Line 1 – Value of r is %d\n”, r );
r = p % q;
printf(“Line 1 – Value of r is %d\n”, r );
r = p++;
printf(“Line 1 – Value of r is %d\n”, r );
r = p–;
printf(“Line 1 – Value of r is %d\n”, r );
}
Once you have completed compiling and executing the program mentioned above, it will produce the
results as follows:
Line 1 – The value of r is 31
Line 2 – The value of r is 11
Line 3 – The value of r is 210
Line 4 – The value of r is 2
Line 5 – The value of r is 1
Line 6 – The value of r is 21
Line 7 – The value of r is 22
Bitwise Operators in C
We use the bitwise operators in C language to perform operations on the available data at a bit
level. Thus, performing a bitwise operation is also called bit-level programming. It is mainly used
in numerical computations for a faster calculation because it consists of two digits – 1 or 0.

Types of Bitwise Operators in C


There are various types of bitwise operators used in all the programming languages. Here is a list of
the ones used in C:
 Bitwise OR Operator
 Bitwise AND Operator
 Unary Operator (Binary One’s complement operator)

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
80
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 Bitwise XOR Operator


 Binary Right Shift Operator
 Binary Left Shift Operator
The table below lists all the Bitwise operations that are supported by the C language. Let us assume
that the variable ‘Q’ holds 13 while a variable ‘P’ holds 60, then:

Operator Meaning Description Examples

| Bitwise OR operator It copies a bit when it exists in either of the (P | Q) = 61, which is,
operands. 0011 1101

& Bitwise AND It copies a bit to the result when it exists in (P & Q) = 12, which
operator both the operands. is, 0000 1100

~ Binary Ones It is a unary operator that has an effect to ‘flip’ (~P ) = ~(60), which
complement the bits. Meaning, all the 0s become 1s and is,. 1100 0011
operator vice-versa.

^ Bitwise XOR It is an exclusive OR operator that copies the (P | Q) = 61, which is,
operator bit when it is set in one of the operands, but not 0011 1101
in both.

>> Shift operator It moves the value of the left operand to the P >> 2 = 15 which is,
(Right) right by the number of bits that the right 0000 1111
operand specifies.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
81
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

<< Shift operator (Left) It moves the value of the right operand to the P << 2 = 240 which
left by the number of bits that the right operand is, 1111 0000
specifies.

Example of Bitwise Operators in C


Let us look at the following example to understand how the bitwise operators work in the C language:
#include <stdio.h>
main() {
unsigned int p = 60; /* 60 = 0011 1100 */
unsigned int q = 13; /* 13 = 0000 1101 */
int r = 0;
r = p | q; /* 61 = 0011 1101 */
printf(“Line 1 – The value of r is %d\n”, r );
r = p & q; /* 12 = 0000 1100 */
printf(“Line 2 – The value of r is %d\n”, r );
r = ~p; /*-61 = 1100 0011 */
printf(“Line 3 – The value of r is %d\n”, r );
r = p ^ q; /* 49 = 0011 0001 */
printf(“Line 4 – The value of r is %d\n”, r );
r = p >> 2; /* 15 = 0000 1111 */
printf(“Line 5 – The value of r is %d\n”, r );
r = p << 2; /* 240 = 1111 0000 */
printf(“Line 6 – The value of r is %d\n”, r );
}
The compilation and execution of the program mentioned above will produce the result as −
Line 1 – The value of c is 61
Line 2 – The value of c is 12
Line 3 – The value of c is -61
Line 4 – The value of c is 49
Line 5 – The value of c is 15
Line 6 – The value of c is 240

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
82
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Here is another example regarding how we can use the bitwise operators in the C language:
// C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main()
{
// p = 5(00000101), q = 9(00001001)
unsigned char p = 5, q = 9;
// The result is 00000001
printf(“p = %d, q = %d\n”, p, q);
printf(“p&q = %d\n”, p & q);
// The result is 00001100
printf(“p^q = %d\n”, p ^ q);
// The result is 00001101
printf(“p|q = %d\n”, p | q);
// The result is 11111010
printf(“~p = %d\n”, p = ~p);
// The result is 00000100
printf(“q>>1 = %d\n”, q >> 1);
// The result is 00010010
printf(“q<<1 = %d\n”, q << 1);
return 0;
}
The output generated from above will be −
p = 5, q = 9
p&q = 1
p^q = 12
p|q = 13
~p = 250
q>>1 = 4
q<<1 = 18
Some Interesting Facts to Consider

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
83
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

1. The right shift operators and left shift operators must not be used for the negative numbers –
When the second (that describes the total number of shifts) operand is a negative number, we witness
an undefined behavior in C. For instance, the results that we get from both 1 >> -1 and 1 << -1 are
undefined. As a matter of fact, if the number gets shifted to be more than the size of the available
integer, then also the behavior will be undefined. For instance, 1 << 33 will be undefined if the storing
of integers occurs using 32 bits. Also, we cannot perform any shift operations if the additive-
expression operand (the operand that decides the total number of shifts) is 0.
Note – This type of behavior is very well-defined in the C++ language.
2. From a perspective of technical interview, the bitwise XOR operator is basically the most
useful one –
This operator is used in various problems. One of the examples here can be “With a set of numbers in
which all the available elements occur even many times except one of the numbers, find the number
that is oddly occurring”. This type of problem can be solved pretty effectively if we do the XOR of all
these numbers.
3. We cannot use the bitwise operators in the place of any logical operator –
The result that we get from a logical operator (&&, ! and ||) is either 1 or 0. But the bitwise
operators, on the other hand, return a value that is an integer. Along with this, a logical operator
would consider any operand that is non-zero to be 1. Let us consider an example of a program
where the results of && and & are different for the very same operands.
4. The bitwise operators should not be used in place of logical operators –
Logical operators (&&, || and !) generate results of either 0 or 1. The bitwise operator, on the other
hand, returns a value or integers. Also, the logical operators consider any non-zero operand as 1. For
example, consider the following program, the results of & and && are different for the same
operands.
#include <stdio.h>
int main()
{
int a = 2, b = 5;
(a & b) ? printf(“False “) : printf(“True “);
(a && b) ? printf(“False “) : printf(“True “);
return 0;
}
The generated output would be:
False True
5. The right-shift and left-shift operators are equivalent to respectively division and
multiplication by 2. But it will work only when the available numbers are positive.
Let us look at an example,

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
84
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

#include <stdio.h>
int main()
{
int a = 19;
printf(“a >> 1 = %d\n”, a >> 1);
printf(“a << 1 = %d\n”, a << 1);
return 0;
}
The generated output would be:
a >> 1 = 9
a << 1 = 38
6. We can use the & operator to check quickly if a number is even or odd –
The value of the given expression would be non-zero (x & 1) if x is odd. In other cases, the value will
be zero.
Let us look at an example,
#include <stdio.h>
int main()
{
int x = 19;
(x & 1) ? printf(“Even”) : printf(“Odd”);
return 0;
}
The generated output would be:
Even

7. We have to use the ~ operator very carefully –


The result obtained from the ~ operator on any small number could be a big number in case we store
the result in an unsigned variable. Also, the result can be a negative number when this result is stored
in a variable that is signed.
Operator Precedence and Associativity in C
The precedence of operators in C dictates the order in which the operators will be evolved in an
expression. Associativity, on the other hand, defines the order in which the operators of the same
precedence will be evaluated in an expression. Also, associativity can occur from either right to left or
left to right.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
85
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Use of the Operator Precedence and Associativity in C


Precedence and Associativity are two of the characters that are used for operators in an expression for
determining the order of sub-expressions when they do not have brackets.
Operator Precedence
Operator precedence helps us determine which of the operators in an expression must be evaluated
first in case the expression consists of more than a single operator.
Example,
50 – 2 * 15 is going to yield 20. It is because it gets evaluated as 50 – (2 * 15), and not as (50 –
2) * 15. The reason here is that subtraction (-) has lower precedence as compared to multiplication
(*).
Operator Associativity
We use associativity when two or more than two operators with the same precedence are present in
the same expression.
Example,
The precedence of Division and Multiplication arithmetic operators is the same. So, let’s say we have
an expression with us which is 6 * 3 / 20. The evaluation of this expression would be (6 * 3) / 20
because the associativity will be left to right for both the operators – multiplication and division. In a
similar case, the calculation of 40 / 4 * 5 would be (40 / 4) * 5 because the associativity would be
from right to left here as well.
Summary of Operator Precedence and Associativity in C
Here is how the operator precedence and associativity work in the C language:

Operator Description of Operator Associativity

. Direct member selection Left to right

-> Indirect member selection Left to right

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
86
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
[] Array element reference Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
87
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
() Functional call Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
88
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
~ Bitwise(1’s) complement Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
89
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
! Logical negation Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
90
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
– Unary minus Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
91
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
+ Unary plus Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
92
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
— Decrement Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
93
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
++ Increment Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
94
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
* Pointer reference Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
95
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
& Dereference (Address) Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
96
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
(type) Typecast (conversion) Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
97
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
sizeof Returns the size of an object Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
98
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
% Remainder Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
99
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
/ Divide Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
* Multiply Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
– Binary minus (subtraction) Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
+ Binary plus (Addition) Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
>> Right shift Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
<< Left shift Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
> Greater than Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
< Less than Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
>= Greater than or equal Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
10
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
<= Less than or equal Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
== Equal to Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
!= Not equal to Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
^ Bitwise exclusive OR Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
& Bitwise AND Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
|| Logical OR Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
| Bitwise OR Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
?: Conditional Operator Right to left
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

CULTSOFT
&& Logical AND Left to right
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

, Separator of expressions Left to right

= Simple assignment Right to left

/= Assign quotient Right to left

*= Assign product Right to left

%= Assign remainder Right to left

-= Assign difference Right to left

+= Assign sum Right to left

|= Assign bitwise OR Right to left

^= Assign bitwise XOR Right to left

&= Assign bitwise AND Right to left

>>= Assign right shift Right to left

<<= Assign left shift Right to left

Some Important Points to Remember

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

1. We only use associativity when we have two or more operators that have the same precedence in an
expression.
The point to note here is that associativity is not applicable when we are defining the order of
evaluation of operands with different levels of precedence.
2. All the operators that have a similar level of precedence have the same associativity. It is very
important, or else the compiler won’t be able to decide what order of evaluation must an expression
follow when it has two operators with the same precedence but different associativity. For example, –
and + have the very same associativity.
3. The associativity and precedence of prefix ++ and postfix ++ are very different from each other.
Here, the precedence of prefix ++ is less as compared to the postfix ++. Thus, their associativity also
turns out to be different. Here, the associativity of prefix ++ is from right to left, while the
associativity of postfix ++ is from left to right.
4. We must use a comma (,) very carefully, as it has the least level of precedence among all the other
operators present in an expression.
5. We don’t have chaining of comparison in the C programming language. The Python language treats
the expressions such as x > y > z as x > y and y > z. No similar type of chaining occurs in the C
program.
Increment and Decrement Operators in C
The decrement (–) and increment (++) operators are special types of operators used in
programming languages to decrement and increment the value of the given variable by 1 (one),
respectively
Types of Increment and Decrement Operators in C
Following types of increment and decrement operators are found in the C language:
 Prefix Increment operator
 Prefix Decrement operator
 Postfix Increment operator
 Postfix Decrement operator
Both the operators vary a lot in their fundamental working. However, we can only use these with
variables, and not with expressions or constants. Read more about the difference between Increment
and Decrement Operators.
Increment Operators
We use increment operators in C to increment the given value of a variable by 1.
For instance,
int a = 1, b = 1;
++b; // valid
++3; // invalid – increment operator is operating on constant value
++(a+b); // invalid – increment operator is operating on expression

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Prefix Increment Operators


The prefix increment operator increments the current value of the available variable immediately, and
only then this value is used in an expression. In simpler words, the value of a variable first gets
incremented and then used inside any expression in the case of an increment operation.
b = ++a;
In this case, the current value of a will be incremented first by 1. Then the new value will be assigned
to b for the expression in which it is used.
Thus, Syntax for Prefix Increment Operator:
++variable;
For example,
#include<stdio.h>
#include<conio.h>
void main()
{
int p,q;
i=10;
p=++q;
printf(“p: %d”,p);
printf(“q: %d”,q);
getch();
}
The output here would be:
p: 11
q: 11
Postfix Increment Operators
The postfix increment operator allows the usage of the current value of a variable in an expression and
then increments its value by 1. In simpler words, the value of a variable is first used inside the
provided expression, and then its value gets incremented by 1.
For example:
b = a++;
In this case, the current value of a is first assigned to b, and after that, a is incremented.
Thus, Syntax for Postfix Increment Operator:
variable++;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

For example,
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
b=10;
a=b++;
printf(“a: %d”,a);
printf(“b: %d”,b);
getch();
}
The output here would be:
a: 10
b: 11
Syntax of Increment Operators
// PREFIX
++x
// POSTFIX
x++
where x is a variable
Example of Increment Operators
#include <stdio.h>
int main() {
int x = 5, y = 5;
// x is displayed
// Then, x is increased to 6.
printf(“%d post-increment n”, x++);
// y is increased to 6
// Then, it is displayed.
printf(“%d pre-incrementn”, ++y);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

return 0;
}
The output here would be:
5 post-increment
6 pre-increment
Decrement Operators
We use decrement operators in C to decrement the given value of a variable by 1.
For instance,
int a = 2, b = 1;
–b; // valid
–5; // invalid – decrement operator is operating on constant value
–(a-b); // invalid – decrement operator is operating on expression
Prefix Decrement Operators
The prefix decrement operator decrements the current value of the available variable immediately, and
only then this value is used in an expression. In simpler words, the value of a variable first gets
decremented and then used inside any expression in the case of a decrement operation.
b = –a;
In this case, the current value of a will be decremented first by 1. Then the new value will be
assigned to b for the expression in which it is used.
Thus, Syntax for Prefix Decrement Operator:
–variable;
For example,
#include<stdio.h>
#include<conio.h>
void main()
{
int p,q;
i=10;
p=–q;
printf(“p: %d”,p);
printf(“q: %d”,q);
getch();

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

}
The output here would be:
p: 9
q: 9
Postfix Decrement Operators
The postfix decrement operator allows the usage of the current value of a variable in an
expression and then decrements its value by 1. In simpler words, the value of a variable is first used
inside the provided expression, and then its value gets decremented by 1. For example:
b = a–;
In this case, the current value of a is first assigned to b, and after that, a is decremented.
Thus, Syntax for Postfix Decrement Operator:
variable–;
For example,
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
b=10;
a=b–;
printf(“a: %d”,a);
printf(“b: %d”,b);
getch();
}
The output here would be:
a: 10
b: 9
Syntax of Increment Operators
// PREFIX
–x
// POSTFIX
x–

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

where x is a variable
Example of Decrement Operators
#include <stdio.h>
int main() {
int x = 5, y = 5;
// x is displayed
// Then, x is decreased to 4.
printf(“%d post-decrement n”, x–);
// y is decreased to 4
// Then, it is displayed.
printf(“%d pre-decrement”, –y);
return 0;
}
The output here would be:
5 post-decrement
4 pre-decrement
Precedence in Increment and Decrement Operators in C
Both of these operators have very high precedence (parentheses are an exception). Also, the
precedence of postfix decrement/ increment operators is higher than that of prefix decrement/
increment operators.
Here is a table that discusses the precedence associativity of these operators:

Description Operators Associativity

postfix decrement operator — left to right

postfix increment operator ++ left to right

parentheses () left to right

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

prefix increment operator ++ right to left

prefix decrement operator — right to left

unary plus + right to left

unary minus – right to left

Multiplication * left to right

Division / left to right

Modulus % left to right

Addition + left to right

Subtraction – left to right

Assignment Operator = right to left

Compound Assignment Operator =, +=, -=, *=, /=, %= right to left

An array of pointers in c
When we require multiple pointers in a C program, we create an array of multiple pointers and use
it in the program. We do the same for all the other data types in the C program.
An Array of Pointers in C
The pointers and arrays are very closely related to one another in the C language. The program
considers an array as a pointer. In simpler words, an array name consists of the addresses of the
elements. Before we understand what an array of pointers is, let us understand more about pointers
and arrays separately.
What is an Array?

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

If we want to include multiple elements in a program with the very same data type, we can use an
array. Let us assume that we are using a total of five integers in any program. There are two different
ways in which we can allocate memory to all of these integers:
 We can create five integers differently;
 We can create an array of all the different integers.
One of the huge advantages of using arrays is that it becomes very easy for a programmer to access all
the elements in the program easily. All the elements can be accessed in a single run of a loop in the
program.
What is a Pointer?
The pointers in C point towards the variables present in a program. They hold the addresses of
the variables. The program will use these addresses to access the variables and modify them.
Here are the three crucial things that come into play when dealing with pointers in C:
 Declaration of the pointer variable
 Initialisation of the pointer variable
 Using the pointer to access the variable
What is an Array of Pointers in C?
When we want to point at multiple variables or memories of the same data type in a C program, we
use an array of pointers.
Let us assume that a total of five employees are working at a cheesecake factory. We can store the
employees’ names in the form of an array. Along with this, we also store the names of employees
working at the office, the library, and the shoe store.
Now, let us assume that once we read all the names of the employees randomly, we want to sort all of
the employees’ names working in the cheesecake factory. Sorting all the employee names requires
reading, swapping, and copying a lot of data. But since we have stored all the employee names in
groups/ arrays, we can directly refer to the array of names of employees working at the cheesecake
factory.
The Application of Arrays of Pointers
Let us assume that we want to build an enclosed system, and this system uses a different kind of
thermometer for measuring the temperature. Now, in this case, we can use an array for holding the
address of memory for every sensor. This way, manipulation of the sensor status becomes very
easy.
Example
The thermo[0] will be holding the 1st sensor’s address.
The thermo[1] will be holding the 2nd sensor’s address and so on.
Now, since it’s an array, it can interact directly with the thermo pointer indexed in the array. Thus, we
will get the 1st sensor’s status with the thermo[0], the second one using the thermo[1], and so on
ahead.
Declaration of an Array of Pointers in C

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

An array of pointers can be declared just like we declare the arrays of char, float, int, etc. The syntax
for declaring an array of pointers would be:
data_type *name_of_array [array_size];
Now, let us take a look at an example for the same,
int *ary[55]
This one is an array of a total of 55 pointers. In simple words, this array is capable of holding the
addresses a total of 55 integer variables. Think of it like this- the ary[0] will hold the address of one
integer variable, then the ary[1] will hold the address of the other integer variable, and so on.
Example
Let us take a look at a program that demonstrates how one can use an array of pointers in C:
#include<stdio.h>
#define SIZE 10
int main()
{
int *arr[3];
int p = 40, q = 60, r = 90, i;
arr[0] = &p;
arr[1] = &q;
arr[2] = &r;
for(i = 0; i < 3; i++)
{
printf(“For the Address = %d\t the Value would be = %d\n”, arr[i], *arr[i]);
}
return 0;
}
The output generated out of the program mentioned above would be like this:
For the Address = 387130656 the Value would be = 40
For the Address = 387130660 the Value would be = 60
For the Address = 387130664 the Value would be = 90
How Does it Work?
Take a look at how we assigned the addresses of the pointers p, q, and r. We first assign the p
variable’s address to the 0th element present in the array. In a similar manner, the 1st and 2nd

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

elements of the array will be assigned with the addresses of q and r. At this very point, the array, arr
would look like this:

The arr[i] provides the address of the array’s ith element. Thus, the arr[0] would return the address of
the variable p, the arr[1] would return the
address of the pointer q, and so on. We use
the * indirection operator to get the value
present at the address. Thus, it would be
like this:
*arr[i]
Thus, *arr[0] would generate the value at
the arr[0] address. In a similar manner, the
*arr[1] would generate the value at the
arr[1] address, and so on.

Exploring File I/O in C📁

Introduction
File handling is a fundamental aspect of programming that allows us to interact with data stored on
our computers. Whether it's reading text from a file, writing data to it, or manipulating its contents,
mastering Input/Output (IO) operations is essential for any developer.
In this article, we would cover some file handling concepts in C, low-level and high-level File I/O,
file descriptors and more.

Importance of File Handling


 When a program is terminated, the entire data is lost. Storing in a file will preserve data even
if the program terminates.
 If you have to enter a large number of data, it'll take sometime. However, if you have a
file containing all the data, you can easily access the contents with few commands.
 File handling enables the reading and writing of configuration files, allowing users to
tailor software settings to their preferences.
 Through file handling, programs that need to exchange data with other programs or systems
can share data in various formats with external entities.
 Regularly saving data to files ensures that valuable information can be restored in case of
system failures or data loss
Getting started with File Handling
At its core, file handling involves performing operations on files which include opening,
reading, writing and closing files. In C programming, file handling is achieved through the
following
 Streams

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 File pointers
 File descriptors.
Let's look at these more closely

Streams
These are a fundamental abstraction for file handling in C. They provide a high-level interface for
reading and writing to files. In C, there are standard streams like stdin(standard input) stdout (standard
output) and stderr (standard error) which are automatically available for input and output.
File Pointers
A file pointer is a mechanism used to keep track of the current position within a file. It determines
where the next read or write operation will occur. File pointers are essential for sequential file access
and help navigate through the file's contents.
File Descriptors
These are low-level integer identifiers that represent open files in C. Each descriptor corresponds to a
particular stream as we found above.
Below is a table to summarize the various descriptors and their corresponding streams.

Integer Value Name Symbolic Constant File Stream

0 Standard Input STDIN_FILENO stdin

1 Standard Output STDOUT_FILENO stdout

2 Standard Error STDERR_FILENO stderr

NOTE
stdin: It is used to read input from the user or another program.
stdout: Used to write output to the user or another program.
stderr: Used to write error messages and other diagnostics output to the user.
Basic operations in File handling with C
There are four (4) basic operations in file handling with C. They are opening, reading, writing and
closing. These operations must be followed in order when handling and manipulating files.
Aside the four (4) basic operations, there are generally two (2) approaches to handling them. They are
low-level approach with system calls and high-level approach with standard library.
Another point to note is that files come in different formats such as csv, binary and text. This
article would focus on the text files only.
Let us look at the basic operations in file handling. For each operation, we would look at its
implementation in both the high-level and low-level approaches.
Opening a File
 This is the first step in file handling. It establishes connection between your program and the
file on disk.
 During file opening, you specify the following parameters

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 File's name
 Location
 Mode with which you want to open the file in. These modes specify what exactly you
would like to do with the file you are opening. These includes: reading only, writing
only, appending etc.
High-Level Approach
FILE *file = fopen("example.txt", "r");
RETURN VALUE: FILE pointer if successful, NULL if otherwise
Low-Level Approach
int fd = open("example.txt", O_RDONLY);
man open
RETURN VALUE: New file descriptor if successful, -1 if an error occurred.
Below is a table to understand various modes and how they correspond to each other in high-level and
low-level approaches.

fopen()
open() flags Usage
mode

r O_RDONLY Opens file for reading

r+ O_RDWR Opens file for reading and writing

O_WRONLY | O_CREAT | Writes to a file. It clears(truncates) everything if there is


w
O_TRUNC already text

O_RDWR | O_CREAT | Opens for reading and writing. The file is created if it
w+
O_TRUNC doesn't exist otherwise it's truncated.

O_WRONLY | O_CREAT | Open for appending (writing at end of file). The file is
a
O_APPEND created if it doesn't exist

Reading from a File


 This involves retrieving data from existing file on disk.
 You can read data character by character, line by line or in larger chunks depending on your
program's requirement.
High-Level Approach
There are two ways to read from files with this approach. They are:
fgets(): This reads texts line by line and stores in a buffer.
FILE *file;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

char buffer[1024];
while(fgets(buffer, sizeof(buffer), file) != NULL) {
// Process each line in the file
}
RETURN VALUE: A string on success, NULL on error.
man fgets
fread(): This reads specified number of bytes from a file or for reading binary files also into a
buffer.
man fread
FILE *file;
char buffer[1024];
size_t bytes_to_read = sizeof(buffer);
size_t bytes_read = fread(buffer, 1, bytes_to_read, file);
RETURN VALUE: Number of items read
Low-Level Approach
This uses the read() function.
char buffer[1024];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1)
// handle error
else
// Process the data in the buffer
NOTE: The fd is the return value of the open function
man read
Writing to a file
 This adds or updates data in a file.
 You can write character by character, line by line or in larger blocks as well.
 Writing is essential for tasks like creating log files, saving program output or storing user-
generated content.
High-Level Approach
This method uses fprintf() (Write formatted text data to a file)
FILE *file = fopen("example.txt", "w"); // Open for writing
fprintf(file, "Hello, %s!\n", "World");

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

man fprintf
fwrite() (Writes a specified number of bytes from the buffer to a file)
FILE *file = fopen("data.bin", "wb"); // Open for binary writing
char data[] = {0x01, 0x02, 0x03};
size_t bytes_to_write = sizeof(data);
size_t bytes_written = fwrite(data, 1, bytes_to_write, file);
man fwrite
Low-Level Approach
write() is the function used here.
int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
const char *text = "Hello, World!\n";
ssize_t bytes_written = write(fd, text, strlen(text));
man write
NOTE: Modify the various modes/flags of the write operation to get the desired results like append
etc.
In the low-level approach, you have more control over the writing process and can directly manipulate
the binary data. However, you need to manage buffering and handle text encoding yourself if you're
working with text files.
Closing a File
 This is the final step in the file handling and it's essential to release the system resources and
ensure data integrity.
 Once you finish reading or writing, you should close the file to free up the file descriptors and
ensure that all pending changes are saved.
 Failing to close a file property can result in resource leaks and data corruption.
High level approach
FILE *file = fopen("example.txt", "w"); // Open for writing
// Write data to the file
fclose(file); // Close the file when done
man fclose
Low level approach
int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644); // Open for writing
// Write data to the file
close(fd); // Close the file descriptor when done

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

man close
Until now you might have realized that there are two approaches to handline files in C. The
commonest one used is the high-level approach. However, let us look at some differences between the
two. This would help inform our decisions as to which of them to use at what point in time.

Aspect High level Approach Low level Approach

File Uses a file stream represented by Uses file descriptors represented by *int* for
representation *FILE**, for file operations file operations

Common Common functions include fopen(), Common functions include open(), close(),
functions fclose(), fgets(), fprintf(), fwrite(). read(), write().

Suitable for both text and binary files, Suitable for both text and binary files, but
Text vs. Binary
with functions handling text encoding you need to handle text encoding and
Files
and formatting. formatting manually if required.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Relies on error codes returned by functions


like read() and write() for error handling.

Uses functions like ferror() and feof()


Error Handling
to handle errors.

Automatically flushes data and


Resource Requires manual closure of file descriptors
releases resources when you use
Cleanup using close() for resource cleanup.
fclose()

Now let's look at some examples with practical questions


QUESTION
Implement a program to read text from a file
SOLUTION
High level approach
#include <stdio.h>
#include <stdlib.h>

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


if (argc != 2) {
printf("Usage: %s source_file\n", argv[0]);
return 1;
}

FILE *source = fopen(argv[1], "r");

if (!source) {
perror("Error");

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

return 1;
}

char buffer[1024];

while (fgets(buffer, sizeof(buffer), source)) {


printf("%s", buffer);
}

fclose(source);

return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

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


if (argc != 2) {
printf("Usage: %s source_file\n", argv[0]);
return 1;
}

int source_fd = open(argv[1], O_RDONLY);

if (source_fd == -1) {
perror("Error");
return 1;
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

char buffer[1024];
ssize_t bytes_read;

while ((bytes_read = read(source_fd, buffer, sizeof(buffer))) > 0) {


if (write(STDOUT_FILENO, buffer, bytes_read) == -1) {
perror("Error");
return 1;
}
}

close(source_fd);

return 0;
}
QUESTION
Implement a program to append some text to a file. This program should take the text from the user
(stdin) and then append to the file
SOLUTION
High level approach
#include <stdio.h>
#include <stdlib.h>

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


if (argc != 2) {
printf("Usage: %s destination_file\n", argv[0]);
return 1;
}

FILE *destination = fopen(argv[1], "a");

if (!destination) {

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

perror("Error");
return 1;
}

char input[1024];

printf("Enter text (Ctrl-D to end):\n");

while (fgets(input, sizeof(input), stdin)) {


fputs(input, destination);
}

fclose(destination);

return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

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


if (argc != 2) {
printf("Usage: %s destination_file\n", argv[0]);
return 1;
}

int destination_fd = open(argv[1], O_WRONLY | O_CREAT | O_APPEND, 0644);

if (destination_fd == -1) {

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

perror("Error");
return 1;
}

char input[1024];

printf("Enter text (Ctrl-D to end):\n");

while (fgets(input, sizeof(input), stdin)) {


if (write(destination_fd, input, strlen(input)) == -1) {
perror("Error");
return 1;
}
}

close(destination_fd);

return 0;
}
QUESTION
Implement a File Copy Program (like cp command)
SOLUTION
High level approach
#include <stdio.h>
#include <stdlib.h>

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


if (argc != 3) {
printf("Usage: %s source_file destination_file\n", argv[0]);
return 1;
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

FILE *source = fopen(argv[1], "rb");


FILE *destination = fopen(argv[2], "wb");

if (!source || !destination) {
perror("Error");
return 1;
}

char buffer[1024];
size_t bytes_read;

while ((bytes_read = fread(buffer, 1, sizeof(buffer), source)) > 0) {


fwrite(buffer, 1, bytes_read, destination);
}

fclose(source);
fclose(destination);

return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

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


if (argc != 3) {
printf("Usage: %s source_file destination_file\n", argv[0]);
return 1;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

int source_fd = open(argv[1], O_RDONLY);


int destination_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (source_fd == -1 || destination_fd == -1) {


perror("Error");
return 1;
}

char buffer[1024];
ssize_t bytes_read;

while ((bytes_read = read(source_fd, buffer, sizeof(buffer))) > 0) {


if (write(destination_fd, buffer, bytes_read) == -1) {
perror("Error");
return 1;
}
}

close(source_fd);
close(destination_fd);

return 0;
}
NOTE: In low-level implementation, the open() function has an optional argument known
as permissions. These are file permissions that you can set to the file are read, write and execute
permissions represented by their numerical values

Exploring File I/O in C📁

#codenewbie#programming#c#beginners

Introduction

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

File handling is a fundamental aspect of programming that allows us to interact with data stored on
our computers. Whether it's reading text from a file, writing data to it, or manipulating its contents,
mastering Input/Output (IO) operations is essential for any developer.
In this article, we would cover some file handling concepts in C, low-level and high-level File I/O,
file descriptors and more.
Importance of File Handling
 When a program is terminated, the entire data is lost. Storing in a file will preserve data
even if the program terminates.
 If you have to enter a large number of data, it'll take sometime. However, if you have a
file containing all the data, you can easily access the contents with few commands.
 File handling enables the reading and writing of configuration files, allowing users to tailor
software settings to their preferences.
 Through file handling, programs that need to exchange data with other programs or systems
can share data in various formats with external entities.
 Regularly saving data to files ensures that valuable information can be restored in case of
system failures or data loss

Getting started with File Handling


At its core, file handling involves performing operations on files which include opening, reading,
writing and closing files. In C programming, file handling is achieved through the following
 Streams
 File pointers
 File descriptors.
Let's look at these more closely
Streams
These are a fundamental abstraction for file handling in C. They provide a high-level interface for
reading and writing to files. In C, there are standard streams like stdin(standard input) stdout (standard
output) and stderr (standard error) which are automatically available for input and output.
File Pointers
A file pointer is a mechanism used to keep track of the current position within a file. It determines
where the next read or write operation will occur. File pointers are essential for sequential file access
and help navigate through the file's contents.
File Descriptors
These are low-level integer identifiers that represent open files in C. Each descriptor corresponds to a
particular stream as we found above.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Below is a table to summarize the various descriptors and their corresponding streams.

Integer Value Name Symbolic Constant File Stream

0 Standard Input STDIN_FILENO stdin

1 Standard Output STDOUT_FILENO stdout

2 Standard Error STDERR_FILENO stderr

NOTE
stdin: It is used to read input from the user or another program.
stdout: Used to write output to the user or another program.
stderr: Used to write error messages and other diagnostics output to the user.
Basic operations in File handling with C
There are four (4) basic operations in file handling with C. They are opening, reading, writing and
closing. These operations must be followed in order when handling and manipulating files.
Aside the four (4) basic operations, there are generally two (2) approaches to handling them. They are
low-level approach with system calls and high-level approach with standard library.
Another point to note is that files come in different formats such as csv, binary and text. This article
would focus on the text files only.
Let us look at the basic operations in file handling. For each operation, we would look at its
implementation in both the high-level and low-level approaches.
Opening a File
 This is the first step in file handling. It establishes connection between your program and the
file on disk.
 During file opening, you specify the following parameters
 File's name
 Location
 Mode with which you want to open the file in. These modes specify what exactly you
would like to do with the file you are opening. These includes: reading only, writing
only, appending etc. Man fopen
High-Level Approach
FILE *file = fopen("example.txt", "r");
RETURN VALUE: FILE pointer if successful, NULL if otherwise
Low-Level Approach
int fd = open("example.txt", O_RDONLY);
man open
RETURN VALUE: New file descriptor if successful, -1 if an error occurred.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Below is a table to understand various modes and how they correspond to each other in high-level and
low-level approaches.

fopen()
open() flags Usage
mode

r O_RDONLY Opens file for reading

r+ O_RDWR Opens file for reading and writing

O_WRONLY | O_CREAT | Writes to a file. It clears(truncates) everything if there is


w
O_TRUNC already text

O_RDWR | O_CREAT | Opens for reading and writing. The file is created if it
w+
O_TRUNC doesn't exist otherwise it's truncated.

O_WRONLY | O_CREAT | Open for appending (writing at end of file). The file is
a
O_APPEND created if it doesn't exist

Reading from a File


 This involves retrieving data from existing file on disk.
 You can read data character by character, line by line or in larger chunks depending on your
program's requirement.
High-Level Approach
There are two ways to read from files with this approach. They are:
fgets(): This reads texts line by line and stores in a buffer.
FILE *file;
char buffer[1024];
while(fgets(buffer, sizeof(buffer), file) != NULL) {
// Process each line in the file
}
RETURN VALUE: A string on success, NULL on error.
man fgets
fread(): This reads specified number of bytes from a file or for reading binary files also into a
buffer.
man fread
FILE *file;
char buffer[1024];
size_t bytes_to_read = sizeof(buffer);
size_t bytes_read = fread(buffer, 1, bytes_to_read, file);
RETURN VALUE: Number of items read

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Low-Level Approach
This uses the read() function.
char buffer[1024];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1)
// handle error
else
// Process the data in the buffer
NOTE: The fd is the return value of the open function
Writing to a file
 This adds or updates data in a file.
 You can write character by character, line by line or in larger blocks as well.
 Writing is essential for tasks like creating log files, saving program output or storing user-
generated content.

High-Level Approach
This method uses fprintf() (Write formatted text data to a file)
FILE *file = fopen("example.txt", "w"); // Open for writing
fprintf(file, "Hello, %s!\n", "World");
fwrite() (Writes a specified number of bytes from the buffer to a file)
FILE *file = fopen("data.bin", "wb"); // Open for binary writing
char data[] = {0x01, 0x02, 0x03};
size_t bytes_to_write = sizeof(data);
size_t bytes_written = fwrite(data, 1, bytes_to_write, file);
Low-Level Approach
write() is the function used here.
int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
const char *text = "Hello, World!\n";
ssize_t bytes_written = write(fd, text, strlen(text));
NOTE: Modify the various modes/flags of the write operation to get the desired results like
append etc.
In the low-level approach, you have more control over the writing process and can directly manipulate
the binary data. However, you need to manage buffering and handle text encoding yourself if you're
working with text files.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Closing a File
 This is the final step in the file handling and it's essential to release the system resources and
ensure data integrity.
 Once you finish reading or writing, you should close the file to free up the file descriptors and
ensure that all pending changes are saved.
 Failing to close a file property can result in resource leaks and data corruption.

High level approach


FILE *file = fopen("example.txt", "w"); // Open for writing
// Write data to the file
fclose(file); // Close the file when done
Low level approach
int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644); // Open for writing
// Write data to the file
close(fd); // Close the file descriptor when done
Until now you might have realized that there are two approaches to handline files in C. The
commonest one used is the high-level approach. However, let us look at some differences between the
two. This would help inform our decisions as to which of them to use at what point in time.

Aspect High level Approach Low level Approach

File Uses a file stream represented by Uses file descriptors represented by *int*
representation *FILE**, for file operations for file operations

Common Common functions include fopen(), Common functions include open(), close(),
functions fclose(), fgets(), fprintf(), fwrite(). read(), write().

Suitable for both text and binary files, Suitable for both text and binary files, but
Text vs. Binary
with functions handling text encoding you need to handle text encoding and
Files
and formatting. formatting manually if required.

Uses functions like ferror() and feof() Relies on error codes returned by functions
Error Handling
to handle errors. like read() and write() for error handling.

Resource Automatically flushes data and releases Requires manual closure of file descriptors
Cleanup resources when you use fclose() using close() for resource cleanup.

Now let's look at some examples with practical questions


QUESTION 1
Implement a program to read text from a file
SOLUTION
High level approach

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s source_file\n", argv[0]);
return 1;
}
FILE *source = fopen(argv[1], "r");
if (!source)
{
perror("Error");
return 1;
}
char buffer[1024];

while (fgets(buffer, sizeof(buffer), source))


{
printf("%s", buffer);
}
fclose(source);
return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

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

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

if (argc != 2) {
printf("Usage: %s source_file\n", argv[0]);
return 1;
}

int source_fd = open(argv[1], O_RDONLY);

if (source_fd == -1) {
perror("Error");
return 1;
}

char buffer[1024];
ssize_t bytes_read;

while ((bytes_read = read(source_fd, buffer, sizeof(buffer))) > 0) {


if (write(STDOUT_FILENO, buffer, bytes_read) == -1) {
perror("Error");
return 1;
}
}

close(source_fd);

return 0;
}
QUESTION 2
Implement a program to append some text to a file. This program should take the text from the user
(stdin) and then append to the file
SOLUTION
High level approach
#include <stdio.h>

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

#include <stdlib.h>

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


if (argc != 2) {
printf("Usage: %s destination_file\n", argv[0]);
return 1;
}

FILE *destination = fopen(argv[1], "a");

if (!destination) {
perror("Error");
return 1;
}

char input[1024];

printf("Enter text (Ctrl-D to end):\n");

while (fgets(input, sizeof(input), stdin)) {


fputs(input, destination);
}

fclose(destination);

return 0;
}

Low level approach


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

#include <fcntl.h>

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


if (argc != 2) {
printf("Usage: %s destination_file\n", argv[0]);
return 1;
}

int destination_fd = open(argv[1], O_WRONLY | O_CREAT | O_APPEND, 0644);

if (destination_fd == -1) {
perror("Error");
return 1;
}

char input[1024];

printf("Enter text (Ctrl-D to end):\n");

while (fgets(input, sizeof(input), stdin)) {


if (write(destination_fd, input, strlen(input)) == -1) {
perror("Error");
return 1;
}
}

close(destination_fd);

return 0;
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

QUESTION 3
Implement a File Copy Program (like cp command)
SOLUTION
High level approach
#include <stdio.h>
#include <stdlib.h>

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


if (argc != 3) {
printf("Usage: %s source_file destination_file\n", argv[0]);
return 1;
}

FILE *source = fopen(argv[1], "rb");


FILE *destination = fopen(argv[2], "wb");

if (!source || !destination) {
perror("Error");
return 1;
}

char buffer[1024];
size_t bytes_read;

while ((bytes_read = fread(buffer, 1, sizeof(buffer), source)) > 0) {


fwrite(buffer, 1, bytes_read, destination);
}

fclose(source);
fclose(destination);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

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


if (argc != 3) {
printf("Usage: %s source_file destination_file\n", argv[0]);
return 1;
}

int source_fd = open(argv[1], O_RDONLY);


int destination_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);

if (source_fd == -1 || destination_fd == -1) {


perror("Error");
return 1;
}

char buffer[1024];
ssize_t bytes_read;

while ((bytes_read = read(source_fd, buffer, sizeof(buffer))) > 0) {


if (write(destination_fd, buffer, bytes_read) == -1) {
perror("Error");
return 1;
}
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

close(source_fd);
close(destination_fd);
return 0;
}
NOTE: In low-level implementation, the open() function has an optional argument known
as permissions. These are file permissions that you can set to the file are read, write and execute
permissions represented by their numerical values

Structures and pointers in C


Even if you can pass a structure as an argument to a function, passing a pointer is more efficient.
The reason being, like other data structures, if a structure is passed to a function, the entire structure
must be copied (remember, all C arguments are passed by value under the hood). The same is true of
all other data structures. So, in general, it is best to use pointers whenever possible for efficiency's
sake, since all that needs to be copied is a memory address and not the entire data structure. Using
pointers with functions, is also more efficient because addresses are typically what string-handling
functions are designed to work with, which makes them easier to pass them around to functions.
Another reason to use pointers is that in some older implementations of C, a structure cannot be
passed as a fuction argument, but a pointer can.
The syntax to declare a pointer to a structure is much the same as for other data structures:
// declare the pointer
struct date * datePtr = NULL;

// assign the pointer to the address of a strcture variable


datePtr = &todaysDate;

// use dereferencing to access any member of the date structure declared by datePtr
(*datePtr).day = 21;
// the parentheses above are required because the dot notation has higher precedence than
// the indirection operator (asterisk). This ensures that the dereferencing takes place
// before the assignment, otherwise it would try to access date with a null pointer

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

However, C has a special operator for structures pointers, ->, the dash and greater than symbols
together, which makes it much easier to dereference structures and access the variables within:
#include <stdio.h>
#include <stdlib.h>

// declaring a struct outside of any function allows it to be used


// by any subsequent function, like a global variable

struct date
{
int month;
int day;
int year;
};

int main (void)


{
// create an instance of the structure called name, and the pointer variable
struct date today, *datePtr;

// immediately assign the pointer to point to the structure address


datePtr = &today;

datePtr->month = 8;
datePtr->day = 25;
datePtr->year = 2018;

printf("Today's date is %i/%i/%i \n", datePtr->month, datePtr->day, datePtr->year);

return 0;
};

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Structures containing pointers


A pointer can also be a member of a structure

// declare a structure type intPtrs


struct intPtrs
{
int *pointer1;
int *pointer2;
};

// create an instance of intPtrs called myPointers


struct intPtrs myPointers;

// declare two int variables to store inside myPointers


int int1 = 100, int2;

myPointers.pointer1 = &int1;
myPointers.pointer2 = &int2;

// dereference the pointer and assign the value to int2


*myPointers.pointer2 = 97;

printf("int1: %i, *myPointers.pointer1: %i \n", int1, *myPointers.pointer1);

printf("int2: %i, *myPointers.pointer2: %i \n", int2, *myPointers.pointer2);


Because the above uses integers (with a known, fixed size), dynamic memory allocation is not
necessary. If strings were used, then memory allocation would be used, because structures do not
allocate space to store strings.

Character arrays or character pointers?

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Both of the below are valid ways to declare structures, and while there are advantages to using
pointers, it is important to understand how they work with structures.
struct names
{
char firstName[20];
char lastName[20];
}
// or
struct pnames
{
char *first;
char *last;
}
To understand the difference, see the two examples below.
// create and initialize an instance of names struct
struct names veep = {"Jane", "Doe"};
Above, the strings are stored inside the structure.
The structure has allocated 40 bytes total to hold the names.
// create and initialize an instance of the pnames struct, which contains pointers
struct pnames treas = {"Joe", "Blow"};
Above, the strings are stored wherever the compiler stores string constants.
The structure holds only the two addresses, which takes a total of 16 bytes on the example PC, so
that is all that is allocated.
The structure pnames allocates no space to store strings.
It can only be used with strings that have had space allocated for them elsewhere, such as string
constants or string arrays.
So, when using pointers in structures, the pointers inside should only be used to manage strings that
were created and allocated elsewhere in the program.
Whenever you have pointers inside a structure, you have to use malloc() or calloc(), otherwise they
will be stored wherever string constants are stored.
Use a pointer to store the address, and use a memory allocation function to allocate just the amount of
memory needed for a string.
The example below shows how to allocate memory for pointers inside structures. It uses s_gets() to
read in the user input, which is similar to scanf, but it will take all user input until it hits a carriage
return or end-of-file character.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

// declare a structure called name, that holds pointers


struct name
{
// using pointers instead of character arrays (j.e. strings)
char * firstName;
char * lastName;
};

// hardcode the length of the character array so it can be passed in as a variable


const int SLEN = 50;

// declare a function getInfo that takes a pointer, and an instance


// of the structure declared in the previous example is passed in as an argument
void getInfo (struct name * pointerToNameStruct)
{
char temp[SLEN];
printf("Please enter your first name: ");
s_gets(temp, SLEN);

//allocate memory to hold name


pointerToNameStruct->firstName = (char *) malloc(strlen(temp) + 1);

//copy the name to allocated memory


strcpy(pointerToNameStruct->firstName, temp);

printf("Please enter your last name: ");


s_gets(temp, SLEN);

pointerToNameStruct->lastName = (char *) malloc(strlen(temp) + 1);


strcpy(pointerToNameStruct->lastName, temp);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

}
In the above, the two strings are not stored in the pointerNameStruct structure itself, just the
addresses. They are stored in the block of memory that is assigned and managed by malloc(). The
strings are read in by s_gets, assigned to a temporary variable with a hardcoded size, and then the only
the amount of required memory is allocated malloc() based on the length, which is determined
by slen.
Recap
This subject is pretty complex, but to recap:
 Structures that contain pointers do not allocate memory to store the data that is pointed
to by its members, only the memory to store the addresses.
 If the pointers are of an unknown size (typically strings), then it is possible to use the
structure itself to work with the data. To do so, use:
 a temporary variable to hold the values,
 dereferencing with the -> symbols to access the member of the structure to work with,
 strlen() to determine size,
 a memory allocation function, e.g. malloc() to assign the amount of memory required,
and put it in the right place in memory,
 and strcpy() to copy the value from the temporary variable to the address pointed to
by structure member.

Unions in C

Introduction
A union is syntactically just like a struct and is used to store data for any one of its members at
any one time. For example:
union value {
long i;
double f;
char c;
char *s;
};

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

union value v;
v.i = 42; // value is now 42
v.c = 'a'; // value is now 'a' (no more 42)

union value *pv = &v;


pv->s = malloc(6); // -> works too
strcpy( pv->s, "hello" );
The size of a union is the size of its largest member.
A common use-case for a union would be in a compiler or interpreter where a token is any one of
a character literal, integer literal, floating-point literal, string literal, identifier, operator, etc. It would
be wasteful to use a struct since only one member would ever have a value.

Initialization
Since all members have the same offset, their order mostly doesn’t matter — except that the first
member is the one that is initialized when an initializer list is used so the value given must be the
same type:
union value v = { 42 }; // as if: v.i = 42
Although 0 can initialize any built-in type.
Alternatively, you can use a designated initializer to specify a member:
union value v = { .c = 'a' };

Which Member?
One obvious problem with a union is, after you store a value in a particular member, how do you later
remember which member that was? With a union by itself, you generally can’t. You need some other
variable to “remember” the member you last stored a value in. Often, this is done using
an enumeration and a struct:
enum token_kind {
TOKEN_NONE,
TOKEN_INT,
TOKEN_FLOAT,
TOKEN_CHAR,
TOKEN_STR
};

struct token {
enum token_kind kind;

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
15
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

union { // "anonymous" union


long i;
double f;
char c;
char *s;
};
};

struct token t = { .kind = TOKEN_CHAR, .c = 'a' };


When a union is used inside a struct, it’s often made an anonymous union, that is a union without a
name. In this case, the union members behave as if they’re direct members of their
enclosing struct except they all have the same offset.
Anonymous unions (and structs) are only supported starting in C11.
Type Punning
Type punning is a technique to read or write an object as if it were of a type other than what it was
declared as. Since this circumvents the type system, you really have to know what you’re doing. In C
(but not C++), a union can be used for type punning. For example, here’s a way to get the value of a
32-bit integer with the high and low order 16-bit halves swapped:
uint32_t swap16of32( uint32_t n ) {
union {
uint32_t u32;
uint16_t u16[2];
} u = { n };
uint16_t const t16 = u.u16[0];
u.u16[0] = u.u16[1];
u.u16[1] = t16;
return u.u32;
}
The union members u32 and u16[2] “overlay” each other allowing you to read and write
a uint32_t as if it were a 2-element array of uint16_t. (You could alternatively write a version that
used uint8_t[4] and reversed the entire byte order depending on your particular need.)
You can also use unions to do type punning of unrelated types, for example int32_t and float allowing
you to access the sign, exponent, and mantissa individually. (However, this is CPU-dependent.)
Restricted Class Hierarchies in C

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Another use for unions is to implement class hierarchies in C, but only “restricted” class hierarchies.
A “restricted” class hierarchy is one used only to implement a solution to a problem where all the
classes are known. Users are not permitted to extend the hierarchy via derivation.
This can be partially achieved via final in C++ or fully achieved via sealed in Java or Kotlin.
Of course C doesn’t have either classes or inheritance, but restricted class hierarchies can be
implemented via structs and a union.
The token example shown previously is simple example of this: all the kinds of tokens are known and
there’s one member in the union to hold the data for each kind. But what if there’s more than one
member per kind?
For a larger example, consider cdecl that is a program that can parse a C or C++ declaration (aka,
“gibberish”) and explain it in English:
cdecl> explain int *const (*p)[4]
declare p as pointer to array 4 of constant pointer to integer
During parsing, cdecl creates an abstract syntax tree (AST) of nodes where each node contains
information for a particular kind of declaration. For example, the previous declaration could be
represented as an AST like (expressed in JSON):
{
name: "p",
kind: "pointer",
pointer: {
to: {
kind: "array",
array: {
size: 4,
of: {
kind: "pointer",
type: "const",
pointer: {
to: {
kind: "built-in type",
type: "int"
}
}
}

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

}
}
}
}
For this example, let’s consider a subset of the kinds of nodes in a C++ declaration (to keep the
example shorter):
enum c_ast_kind {
K_BUILTIN, // e.g., int
K_CLASS_STRUCT_UNION,
K_TYPEDEF,
K_ARRAY,
K_ENUM,
K_POINTER,
K_REFERENCE, // C++ reference
K_CONSTRUCTOR, // C++ constructor
K_DESTRUCTOR, // C++ destructor
K_FUNCTION,
K_OPERATOR, // C++ overloaded operator
// ...
};
typedef enum c_ast_kind c_ast_kind_t;
And declare some structs to contain the information needed for each kind:
struct c_array_ast {
c_ast_t *of_ast; // array of ...
unsigned size;
};

struct c_enum_ast {
c_ast_t *of_ast; // fixed type, if any
unsigned bit_width; // width when > 0

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

char const *enum_name; // enumeration name


};

struct c_function_ast {
c_ast_t *ret_ast; // return type
c_ast_list_t param_ast_list; // parameters
};

struct c_operator_ast {
c_ast_t *ret_ast; // return type
c_ast_list_t param_ast_list; // parameters
c_operator_t const *operator; // operator info
};

struct c_ptr_ref_ast {
c_ast_t *to_ast; // pointer/ref to ...
};

struct c_typedef_ast {
c_ast_t const *for_ast; // typedef for ...
unsigned bit_width; // width when > 0
};
Notice that, of the AST information declared thus far, there are similarities, specifically:
1. The nodes point to one other node and the pointer is declared first.
2. Functions and operators both have return types and parameter lists and the parameter lists are
declared second.
3. For nodes that have bit-field widths, the width is alternatively declared second.
The fact that the same members in different structs are at the same offset is convenient because it
means that code that, say, iterates over the parameters of a function will also work for the parameters
of an operator. Having noticed this, we can make an effort to keep the same members in any
remaining structs at the same offsets. For example, the information for K_BUILTIN could be declared
as:
struct c_builtin_ast {

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

unsigned bit_width; // width when > 0


};
because that’s all the information that’s needed for a built-in type. However, the bit_width member
wouldn’t be at the same offset as the same member in either c_enum_ast or c_typedef_ast. To fix that
so code that accesses bit_width can do so for any type that has it, we need to insert an unused pointer
(a void pointer will do):
struct c_builtin_ast {
void *reserved; // instead of for/to
unsigned bit_width; // width when > 0
};
If you think inserting unused members might waste space, remember that, once all these structs are
put into the same union, the union will be the size of the largest member anyway; hence inserting
unused members doesn’t waste space.
While using a named member like reserved is fine, if you want to help guarantee that the member can
never be accessed directly, you can employ a macro:
#define DECL_UNUSED(T) \
_Alignas(T) char UNIQUE_NAME(unused)[ sizeof(T) ]

struct c_builtin_ast {
DECL_UNUSED(c_ast_t*); // instead of for/to
unsigned bit_width; // width when > 0
};
See here for details on UNIQUE_NAME.
We can apply the same fix for the information for K_CONSTRUCTOR so param_list is at the
same offset as in c_function_ast and c_operator_ast (constructors don’t have return types):
struct c_ctor_ast {
DECL_UNUSED(c_ast_t*); // instead of ret_ast
c_ast_list_t param_ast_list; // parameter(s)
};
And again apply the same fix for the information for K_CLASS_STRUCT_UNION so csu_name is at
the same offset as enum_name in c_enum_ast:
struct c_csu_ast {
DECL_UNUSED(c_ast_t*); // instead of for/to
DECL_UNUSED(unsigned); // instead of bit_width

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

char const *csu_name;


};
Given all those declarations (assume that for any struct c_X_ast, there’s a typedef struct c_X_ast
c_X_ast_t), we can now put them all inside an anonymous union inside a struct for an AST node:
struct c_ast {
c_ast_kind_t kind;
char const *name;
c_type_t type;
// ...

union {
c_array_ast_t array;
c_builtin_ast_t builtin;
c_csu_ast_t csu;
c_ctor_ast_t ctor;
c_enum_ast_t enum_;
c_function_ast_t func;
c_operator_ast_t oper;
c_ptr_ref_ast_t ptr_ref;
c_typedef_ast_t tdef;
// ...
};
};
Safeguards
One problem with this approach is that, if you modify any of the structs, you might
inadvertently change the offset of some member so that it no longer is at the same offset as the
same member in another struct. One way to guard against this is via offsetof and _Static_assert:
static_assert(
offsetof( c_operator_ast_t, param_ast_list ) ==
offsetof( c_function_ast_t, param_ast_list ),
"offsetof param_ast_list in c_operator_ast_t & c_function_ast_t must equal"
);

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

static_assert(
offsetof( c_csu_ast_t, csu_name ) ==
offsetof( c_enum_ast_t, enum_name ),
"offsetof csu_name != offsetof enum_name"
);

// More for other members ....


Now you’ll get a compile-time error if any of the offsets change inadvertently.

Conclusion
Take-aways for unions in C:
 They can be used either for storing data for any one member at any one time or for type
punning.
 For type punning very different types, the order of bytes is CPU-dependent.
 They can be used to implement restricted class hierarchies.

Library Functions in C
When it comes to the programming world, library functions play an important role. Library
functions help the programming language to perform desirable actions.
What is Library Functions in C?
All the programming languages contain functions. Library functions in C are also inbuilt
functions in C language.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

These

inbuilt functions are located in some common location, and it is known as the library. All the
functions are used to execute a particular operation. These library functions are generally
preferred to obtain the predefined output. Also, the actions of these functions are present in their
header files.

Library Functions in Different Header Files


Here in this table-picture, there are some header files with their meanings.

Header file Description

stdio.h This is standard input/output header file in which Input/Output functions are declared

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
7
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

conio.h This is console input/output header file

string.h All string related functions are defined in this header file

stdlib.h This header file contains general functions used in C programs

math.h All maths related functions are defined in this header file

time.h This header file contains time and clock related functions

ctype.h All character handling functions are defined in this header file

stdarg.h Variable argument functions are declared in this header file

signal.h Signal handling functions are declared in this file

setjmp.h It includes all jump functions

locale.h It includes locale functions

errno.h Error handling functions are given in this file

assert.h It includes diagnostics functions

Advantages of Using C library Functions

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
8
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

1. The Execution: One of the most significant reasons for utilising the library functions is that
these functions are easy-to-use, and have gone through strict testing.
2. The Functions to Boost the Performance: The standard library functions are very popular.
And, that is the reason developers are trying their best to polish them. During this process, they
come up with an efficient code almost every time to boost the performance.
3. Can Save a Lot of Time: The best part is you don’t need to create basic functions, like
calculating the square root and more, because we already have these. So, the conclusion is,
we can save a lot of time here.
4. These Functions are Convenient: The best quality of an application is that it should work
every time and everywhere. These library functions assist you in this particular phenomenon.

Example of Library Function: Using sqrt


#include <stdio.h>
#include <math.h>
int main(int argc, const char * argv[])
{
/* Explain temporary variables */
double value;
double result;
/* Provide the value we will find the sqrt of */
value = 36;
/* Determine the square root of value */
result = sqrt(value);
/* Show the result of the calculation */
printf(“The Square Root of %f is %f\n”, value, result);
return 0;
}
Output: The Square Root of 36.000000 is 6.000000

Tokens in C
Tokens are some of the most important elements used in the C language for creating a program.
One can define tokens in C as the smallest individual elements in a program that is meaningful to
the functioning of a compiler.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
16
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

A token is the smallest unit used in a C program. Each and every punctuation and word that you
come across in a C program is token. A compiler breaks a C program into tokens and then
proceeds ahead to the next stages used in the compilation process.
Use of the Tokens in C
For instance, without words, you cannot create any sentence- similarly, you cannot create any
program without using tokens in C language. Thus, we can also say that tokens are the building
blocks or the very basic components used in creating any program in the C language.
Classification and Types of Tokens in C
Here are the categories in which we can divide the token in C language:
 Identifiers in C
 Keywords in C
 Operators in C
 Strings in C
 Special Characters in C
 Constant in C
Let’s look at each of these- one by one in detail:
Identifiers in C
These are used to name the arrays, functions, structures, variables, etc. The identifiers are user-
defined words in the C language. These can consist of lowercase letters, uppercase letters, digits,
or underscores, but the starting letter should always be either an alphabet or an underscore. We
cannot make use of identifiers in the form of keywords. Here are the rules that we must follow
when constructing the identifiers:
 The identifiers must not begin with a numerical digit.
 The first character used in an identifier should be either an underscore or an alphabet.
After that, any of the characters, underscores, or digits can follow it.
 Both- the lowercase and uppercase letters are distinct in an identifier. Thus, we can
safely say that an identifier is case-sensitive.
 We cannot use an identifier for representing the keywords.
 An identifier does not specify blank spaces or commas.
 The maximum length of an identifier is 31 characters.
 We must write identifiers in such a way that it is not only meaningful- but also easy to read
and short.
Keywords in C

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

We can define the keywords as the reserved or pre-defined words that hold their own importance.
It means that every keyword has a functionality of its own. Since the keywords are basically
predefined words that the compilers use, thus we cannot use them as the names of variables. If we
use the keywords in the form of variable names, it would mean that we assign a different meaning
to it- something that isn’t allowed. The C language provides a support for 32 keywords, as
mentioned below:

auto enum const goto

double case float default

struct register unsigned sizeof

int typedef short volatile

break extern continue if

else char for do

switch return void static

long union signed while

Operators in C
The operators in C are the special symbols that we use for performing various functions.
Operands are those data items on which we apply the operators. We apply the operators in
between various operands. On the basis of the total number of operands, here is how we
classify the operators:

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
1
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

 Unary Operator
 Binary Operator
 Ternary Operator

Unary Operator
The unary operator in c is a type of operator that gets applied to one single operand, for example: (–)
decrement operator, (++) increment operator, (type)*, sizeof, etc.
Binary Operator
Binary operators are the types of operators that we apply between two of the operands. Here is a list
of all the binary operators that we have in the C language:
 Relational Operators
 Arithmetic Operators
 Logical Operators
 Shift Operators
 Conditional Operators
 Bitwise Operators
 Misc Operator
 Assignment Operator

Ternary Operator
Using this operator would require a total of three operands. For instance, we can use the ?: in
place of the if-else conditions.
Strings in C
The strings in C always get represented in the form of an array of characters. We have a ‘\0′ null
character at the end of any string- thus, this null character represents the end of that string. In C
language, double quotes enclose the strings, while the characters get enclosed typically within various
single characters. The number of characters in a string decides the size of that string.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
2
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Now, there are different ways in which we can describe a string:


char x[9] = “chocolate’; // Here, the compiler allocates a total of 9 bytes to the ‘x’
array.
char x[] = ‘chocolate’; // Here, the compiler performs allocation of memory during
the run time.
char x[9] = {‘c’,’h’,’o’,’c’,’o’,’l’,’a’,’t’,’e’,’\0′}; // Here, we are representing the
string in the form of the individual characters that it has.

Special Characters in C
We also use some of the special characters in the C language, and all of them hold a special meaning
that we cannot use for any other purpose.
 () Simple brackets – We use these during function calling as well as during function
declaration. For instance, the function printf() is pre-defined.
 [ ] Square brackets – The closing and opening brackets represent the multidimensional and
single subscripts.
 (,) Comma – We use the comma for separating more than one statement, separating the
function parameters used in a function call, and for separating various variables when we
print the value of multiple variables using only one printf statement.
 { } Curly braces – We use it during the closing as well as opening of any code. We also
use the curly braces during the closing and opening of the loops.
 (*) Asterisk – We use this symbol for representing the pointers and we also use this
symbol as a type of operator for multiplication.
 (#) Hash/preprocessor – We use it for the preprocessor directive. This processor basically
denotes that the user is utilizing the header file.
 (.) Period – We use the period symbol for accessing a member of a union or a structure.
 (~) Tilde – We use this special character in the form of a destructor for free memory.
Constant in C
Constant is basically a value of a variable that does not change throughout a program. The constants
remain the same, and we cannot change their value whatsoever. Here are two of the ways in which we
can declare a constant:

 By using a #define pre-processor


 By using a const keyword
Here is a list of the types of constants that we use in the C language:

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

Type of Constant Example

Floating-point constant 25.7, 87.4, 13.9, etc.

Integer constant 20, 41, 94, etc.

Hexadecimal constant 0x5x, 0x3y, 0x8z, etc.

Octal constant 033, 099, 077, 011, etc.

String constant “c++”, “.net”, “java”, etc.

Character constant ‘p’, ‘q’, ‘r’, etc.

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join

JOIN OUR COMMUNITY


FOR EXCITING UPDATES
LIKE THAT

CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
5

You might also like