c Programming Complete Notes
c Programming Complete Notes
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.
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()
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
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.
We give a variable a meaningful name when we create it. Here are the rules that we must
follow when naming it:
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
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.
int 1var; // it is incorrect – the name of the variable should not start using a number
int my$var // it is incorrect – no special characters should be in the name of the variable
int my var; // it is incorrect – there must be no spaces in the name 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.
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:
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
6
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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.
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
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
11
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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.
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
Integer constants
int unsigned int 2000u, 5000U, etc.
500.987654321
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
18
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
19
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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
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:
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
23
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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:
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.
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:
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
long long int %lld, %lli -(263 – 1) to 263 – 1 (It will be added by the C99 64
standard)
unsigned long %llu 264 – 1 (It will be added by the C99 standard) 64
long int
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
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
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
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.
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
41
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
42
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
#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
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
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
50
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
scanf(“%lf”, ¢imeter);
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;
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
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,
};
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
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.
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
57
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
60
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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.
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
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:
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:
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
70
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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.
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:
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
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:
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:
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.
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.
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.
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
75
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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:
% The modulus operator and the remainder after the division of an integer var = B % A = 0
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:
++ Increase of the integer value by the increment operator by one var = A++
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.
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
80
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
| 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.
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
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
85
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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
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
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:
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
12
5
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
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.
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.
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.
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
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
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.
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
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];
fclose(source);
return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
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;
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>
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];
fclose(destination);
return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
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];
close(destination_fd);
return 0;
}
QUESTION
Implement a File Copy Program (like cp command)
SOLUTION
High level approach
#include <stdio.h>
#include <stdlib.h>
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
13
9
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
if (!source || !destination) {
perror("Error");
return 1;
}
char buffer[1024];
size_t bytes_read;
fclose(source);
fclose(destination);
return 0;
}
Low level approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
14
0
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
char buffer[1024];
ssize_t bytes_read;
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
#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
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.
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
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
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.
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.
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];
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;
}
if (source_fd == -1) {
perror("Error");
return 1;
}
char buffer[1024];
ssize_t bytes_read;
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>
if (!destination) {
perror("Error");
return 1;
}
char input[1024];
fclose(destination);
return 0;
}
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>
if (destination_fd == -1) {
perror("Error");
return 1;
}
char input[1024];
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>
if (!source || !destination) {
perror("Error");
return 1;
}
char buffer[1024];
size_t bytes_read;
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>
char buffer[1024];
ssize_t bytes_read;
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
// 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>
struct date
{
int month;
int day;
int year;
};
datePtr->month = 8;
datePtr->day = 25;
datePtr->year = 2018;
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
myPointers.pointer1 = &int1;
myPointers.pointer2 = &int2;
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
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)
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
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
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
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
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"
);
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.
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
string.h All string related functions are defined in this header file
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
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.
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:
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
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:
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
3
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
4
C LANGUAGE COMPLETE TUTORIAL CULTSOFT (CONTENT Dev TEAM) SCAN ME To Join
CULTSOFT
Community Whatsapp Link :- https://chat.whatsapp.com/IbW1jDBEVpCEX2mLAZ5NM3
17
5