0% found this document useful (0 votes)
11 views94 pages

UNIT 1 Introduction

Uploaded by

Chetan Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views94 pages

UNIT 1 Introduction

Uploaded by

Chetan Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

What is C?

 C Basics
 C Variables and Constants
 C Data Types
 C Input and Output
 C Operators
 C Control Statements Decision-Making
 C Functions
 C Arrays & Strings
 C Pointers
 C User-Defined Data Types

 C Language Introduction
 Features of C Programming Language
 C Programming Language Standard
 Setting Up C Development Environment
 C Hello World Program
 Compiling a C Program: Behind the Scenes
 C Comments
 Tokens in C
 C Identifiers
 Keywords in C
C Language Introduction

What is C?
C is a
 general-purpose, procedural, high-level programming language
 a powerful and flexible language
 used in the development of computer software and applications, system
programming, games, web development, and more
 was developed by Dennis M. Ritchie at the Bell Telephone Laboratories in
1972
 mainly as a system programming language to write the UNIX operating
system.
 one of the most widely used programming language
 known for its simplicity and efficiency.
 best choice to start with programming as it gives you a foundational
understanding of programming
The main features of the C language :

 Low-level Memory Access


 Clean Syntax
 Procedural Language
 Fast and Efficient
 Modularity
 Statically Type
 General-Purpose Language
 Rich set of built-in Operators
 Libraries with Rich Functions
 Middle-Level Language
 Portability
 Easy to Extend
1. Procedural Language
In a procedural language like C step by step, predefined instructions are carried out. C program
may contain more than one function to perform a particular task. New people to programming
will think that this is the only way a particular programming language works. There are other
programming paradigms as well in the programming world. Most of the commonly used
paradigm is an object-oriented programming language.

2. Fast and Efficient


Newer languages like Java, python offer more features than c programming language but due to
additional processing in these languages, their performance rate gets down effectively. C
programming language as the middle-level language provides programmers access to direct
manipulation with the computer hardware but higher-level languages do not allow this. That’s one
of the reasons C language is considered the first choice to start learning programming languages.
It’s fast because statically typed languages are faster than dynamically typed languages.

3. Modularity
The concept of storing C programming language code in the form of libraries for further future
uses is known as modularity. This programming language can do very little on its own most of its
power is held by its libraries. C language has its own library to solve common problems.

4. Statically Type
C programming language is a statically typed language . Meaning the type of variable is checked
at the time of compilation but not at run time. This means each time a programmer types a
program they have to mention the type of variables used.

5. General-Purpose Language
From system programming to photo editing software, the C programming language is used in
various applications. Some of the common applications where it’s used are as follows:
 Operating systems: Windows, Linux, iOS, Android, OXS
 Databases: PostgreSQL, Oracle, MySQL, MS SQL Server, etc.

6. Rich set of built-in Operators


It is a diversified language with a rich set of built-in operators which are used in writing complex
or simplified C programs.

7. Libraries with Rich Functions


Robust libraries and functions in C help even a beginner coder to code with ease.

8. Middle-Level Language
As it is a middle-level language so it has the combined form of both capabilities of assembly
language and features of the high-level language .

9. Portability
C language is lavishly portable as programs that are written in C language can run and compile
on any system with either no or small changes.

10. Easy to Extend


Programs written in C language can be extended means when a program is already written in it
then some more features and operations can be added to it.
Brief History of C Language
1. 1960 - ALGOL - Developed by International Group
2. 1967 - BCPL - Developed by Martin Richards
3. 1970 - B - Developed by Ken Thompson
4. 1972 - C - Developed by Dennis M. Ritchie
5. 1978 - K&R C - Developed by Brian w. Kernighan and Dennis M. Ritchie
6. 1989 - ANSI C - Developed by ANSI Committee
7. 1990 - ANSI/ISO C - Standardized by ISO

Many of the C projects that exist today were started decades ago.

The UNIX operating system’s development started in 1969, and its code was rewritten in C in 1972.
The C language was actually created to move the UNIX kernel code from assembly to a higher-level
language, which would do the same tasks with fewer lines of code.
Oracle database development started in 1977, and its code was rewritten from assembly to C in
1983. It became one of the most popular databases in the world.
In 1985 Windows 1.0 was released. Although Windows source code is not publicly available, it’s
been stated that its kernel is mostly written in C, with some parts in assembly.
Linux kernel development started in 1991, and it is also written in C. The next year, it was released
under the GNU license and was used as part of the GNU Operating System. The GNU operating
system itself was started using C and Lisp programming languages, so many of its components are
written in C.
But C programming isn’t limited to projects that started decades ago, when there weren’t as many
programming languages as today. Many C projects are still started today; there are some good
reasons for that.

How is the World Powered by C?


Despite the prevalence of higher-level languages, C continues to empower the world. The following
are some of the systems that are used by millions and are programmed in the C language.

Microsoft Windows
Microsoft’s Windows kernel is developed mostly in C, with some parts in assembly language. For
decades, the world’s most used operating system, with about 90 percent of the market share, has
been powered by a kernel written in C.
Linux
Linux is also written mostly in C, with some parts in assembly. About 97 percent of the world’s 500
most powerful supercomputers run the Linux kernel. It is also used in many personal computers.
Mac
Mac computers are also powered by C, since the OS X kernel is written mostly in C. Every program
and driver in a Mac, as in Windows and Linux computers, is running on a C-powered kernel.
Mobile
iOS, Android and Windows Phone kernels are also written in C. They are just mobile adaptations of
existing Mac OS, Linux and Windows kernels. So smartphones we use every day are running on a
C kernel.
Databases
The world’s most popular databases, including Oracle Database, MySQL, MS SQL Server,
and PostgreSQL, are coded in C (the first three of them actually both in C and C++).
Databases are used in all kind of systems: financial, government, media, entertainment,
telecommunications, health, education, retail, social networks, web, and the like.
3D Movies
3D movies are created with applications that are generally written in C and C++. Those applications
need to be very efficient and fast, since they handle a huge amount of data and do many calculations
per second. The more efficient they are, the less time it takes for the artists and animators to
generate the movie shots, and the more money the company saves.

Embedded Systems
The alarm clock that wakes you up is likely programmed in C.
Then you use your microwave or coffee maker to make your breakfast.
They are also embedded systems and therefore are probably programmed in C.
You turn on your TV or radio while you eat your breakfast. Those are also embedded systems,
powered by C. When you open your garage door with the remote control you are also using
an embedded system that is most likely programmed in C.
You get to the store, park your car and go to a vending machine to get a soda. What language did
they use to program this vending machine? Probably C. Then you buy something at the store. The
cash register is also programmed in C. And when you pay with your credit card? You guessed it:
the credit card reader is, again, likely programmed in C.

All those devices are embedded systems. They are like small computers that have
a microcontroller/microprocessor inside that is running a program, also called firmware, on
embedded devices. That program must detect key presses and act accordingly, and also display
information to the user. For example, the alarm clock must interact with the user, detecting what
button the user is pressing and, sometimes, how long it is being pressed, and program the device
accordingly, all while displaying to the user the relevant information. The anti-lock brake system of
the car, for example, must be able to detect sudden locking of the tires and act to release the
pressure on the brakes for a small period of time, unlocking them, and thereby preventing
uncontrolled skidding. All those calculations are done by a programmed embedded system.
Although the programming language used on embedded systems can vary from brand to brand, they
are most commonly programmed in the C language, due to the language’s features of flexibility,
efficiency, performance, and closeness to the hardware.

Application of C
 Operating systems: C is widely used for developing operating systems such as Unix, Linux,
and Windows.
 Embedded systems: C is a popular language for developing embedded systems such as
microcontrollers, microprocessors, and other electronic devices.
 System software: C is used for developing system software such as device drivers, compilers,
and assemblers.
 Networking: C is widely used for developing networking applications such as web servers,
network protocols, and network drivers.
 Database systems: C is used for developing database systems such as Oracle, MySQL, and
PostgreSQL.
 Gaming: C is often used for developing computer games due to its ability to handle low-level
hardware interactions.
 Artificial Intelligence: C is used for developing artificial intelligence and machine learning
applications such as neural networks and deep learning algorithms.
 Scientific applications: C is used for developing scientific applications such as simulation
software and numerical analysis tools.
 Financial applications: C is used for developing financial applications such as stock market
analysis and trading systems.

Why is the C Programming Language Still Used?


There are many programming languages, today, that allow developers to be more productive than
with C for different kinds of projects. There are higher level languages that provide much larger
built-in libraries that simplify working with JSON, XML, UI, web pages, client requests, database
connections, media manipulation, and so on.
But despite that, there are plenty of reasons to believe that C programming will remain active for a
long time.
In programming languages one size does not fit all. Here are some reasons that C is unbeatable, and
almost mandatory, for certain applications.

Portability and Efficiency


C is almost a portable assembly language. It is as close to the machine as possible while it is almost
universally available for existing processor architectures. There is at least one C compiler for almost
every existent architecture. And nowadays, because of highly optimized binaries generated by
modern compilers, it’s not an easy task to improve on their output with hand written assembly.
Such is its portability and efficiency that “compilers, libraries, and interpreters of other
programming languages are often implemented in C”. Interpreted languages like Python, Ruby,
and PHP have their primary implementations written in C. It is even used by compilers for other
languages to communicate with the machine. For example, C is the intermediate language
underlying Eiffel and Forth. This means that, instead of generating machine code for every
architecture to be supported, compilers for those languages just generate intermediate C code, and
the C compiler handles the machine code generation.
C has also become a lingua franca for communicating between developers.
As Alex Allain, Dropbox Engineering Manager and creator of Cprogramming.com, puts it:
C is a great language for expressing common ideas in programming in a way that most
people are comfortable with. Moreover, a lot of the principles used in C – for
instance, argc and argv for command line parameters, as well as loop constructs and
variable types – will show up in a lot of other languages you learn so you’ll be able to
talk to people even if they don’t know C in a way that’s common to both of you.

Memory Manipulation
Arbitrary memory address access and pointer arithmetic is an important feature that makes C a
perfect fit for system programming (operating systems and embedded systems).
At the hardware/software boundary, computer systems and microcontrollers map their peripherals
and I/O pins into memory addresses. System applications must read and write to those custom
memory locations to communicate with the world. So C’s ability to manipulate arbitrary memory
addresses is imperative for system programming.

Deterministic Usage of Resources


A common language feature that system programming cannot rely on is garbage collection, or even
just dynamic allocation for some embedded systems. Embedded applications are very limited in
time and memory resources. They are often used for real-time systems, where a non-deterministic
call to the garbage collector cannot be afforded. And if dynamic allocation cannot be used because
of the lack of memory, it is very important to have other mechanisms of memory management, like
placing data in custom addresses, as C pointers allow. Languages that depend heavily on dynamic
allocation and garbage collection wouldn’t be a fit for resource-limited systems.

Code Size
C has a very small runtime. And the memory footprint for its code is smaller than for most other
languages.
When compared to C++, for example, a C-generated binary that goes to an embedded device is
about half the size of a binary generated by similar C++ code. One of the main causes for that is
exceptions support.
Lingua Franca
As already mentioned, C is a lingua franca for developers. Many implementations of new
algorithms in books or on the internet are first (or only) made available in C by their authors. This
gives the maximum possible portability for the implementation. I’ve seen programmers struggling
on the internet to rewrite a C algorithm to other programming languages because he or she didn’t
know very basic concepts of C.
Be aware that C is an old and widespread language, so you can find all kind of algorithms written in
C around the web. Therefore, you’ll very likely benefit from knowing this language.
Understand the Machine (Think in C)
When we discuss the behaviour of certain portions of code, or certain features of other languages,
with colleagues, we end up “talking in C:” Is this portion passing a “pointer” to the object or
copying the entire object? Could any “cast” be happening here? And so on.

We would rarely discuss (or think) about the assembly instructions that a portion of code is
executing when analysing the behaviour of a portion of code of a high-level language. Instead,
when discussing what the machine is doing, we speak (or think) pretty clearly in C.

Moreover, if you can’t stop and think that way about what you are doing, you may end up
programming with some sort of superstition about how (magically) things are done.
Work on Many Interesting C Projects
Many interesting projects, from big database servers or operating system kernels, to small
embedded applications you can even do at home for your personal satisfaction and fun, are done in
C. There is no reason to stop doing things you may love for the single reason that you don’t know
an old and small, but strong and time-proven programming language like C.

Conclusion
The C programming language doesn’t seem to have an expiration date. It’s closeness to the
hardware, great portability and deterministic usage of resources makes it ideal for low level
development for such things as operating system kernels and embedded software. Its versatility,
efficiency and good performance makes it an excellent choice for high complexity data
manipulation software, like databases or 3D animation. The fact that many programming languages
today are better than C for their intended use doesn’t mean that they beat C in all areas. C is still
unsurpassed when performance is the priority.
The world is running on C-powered devices. We use these devices every day whether we realize it
or not. C is the past, the present, and, as far as we can see, still the future for many areas of
software.
Beginning with C programming:

Writing the First Program in C


The following code is one of the simplest C programs that will help us the basic syntax structure
of a C program.
Example:

#include <stdio.h>

int main () {

int a = 10;

printf ("%d", a);

return 0;

Output
10
Structure of the C program
By structure, it is meant that any program can be written in this structure only. Writing a C
program in any other structure will hence lead to a Compilation Error.
The structure of a C program is as follows:

Components of a C Program:
1. Header Files Inclusion – Line 1 [#include <stdio.h>]
The first and foremost component is the inclusion of the Header files in a C program. A header
file is a file with extension .h which contains C function declarations and macro definitions to be
shared between several source files. All lines that start with # are processed by a pre-processor
which is a program invoked by the compiler. In the above example, the pre-processor copies the
pre-processed code of stdio.h to our file. The .h files are called header files in C.
Some of the C Header files:
 stddef.h – Defines several useful types and macros.
 stdint.h – Defines exact width integer types.
 stdio.h – Defines core input and output functions
 stdlib.h – Defines numeric conversion functions, pseudo-random network generator, and
memory allocation
 string.h – Defines string handling functions
 math.h – Defines common mathematical functions.
2. Main Method Declaration – Line 2 [int main ()]
The next part of a C program is to declare the main () function. It is the entry point of a C
program and the execution typically begins with the first line of the main (). The empty brackets
indicate that the main doesn’t take any parameter. The int that was written before the main
indicates the return type of main (). The value returned by the main indicates the status of
program termination.

3. Body of Main Method – Line 3 to Line 6 [enclosed in {}]


The body of a function in the C program refers to statements that are a part of that function. It can
be anything like manipulations, searching, sorting, printing, etc. A pair of curly brackets define
the body of a function. All functions must start and end with curly brackets.
4. Statement – Line 4 [printf (“Hello World”);]
Statements are the instructions given to the compiler. In C, a statement is always terminated by
a semicolon (;). In this particular case, we use printf () function to instruct the compiler to display
“Hello World” text on the screen.

5. Return Statement – Line 5 [return 0;]


The last part of any C function is the return statement. The return statement refers to the return
values from a function. This return statement and return value depend upon the return type of the
function. The return statement in our program returns the value from main (). The returned value
may be used by an operating system to know the termination status of your program. The value 0
typically means successful termination.

How to Execute the Above Program?


In order to execute the above program, we need to first compile it using a compiler and then we
can run the generated executable. There are online IDEs available for free ike GeeksforGeeksIDE,
that can be used to start development in C without installing a compiler.
1. Windows: There are many free IDEs available for developing programs in C like Code
Blocks and Dev-CPP. IDEs provide us with an environment to develop code, compile it and
finally execute it. We strongly recommend Code Blocks.
2. Linux: GCC compiler comes bundled with Linux which compiles C programs and generates
executables for us to run. Code Blocks can also be used with Linux.
3. macOS: macOS already has a built-in text editor where you can just simply write the code
and save it with a “.c” extension.

C Comments
The comments in C are human-readable explanations or notes in the source code of a C program.
A comment makes the program easier to read and understand.
These are the statements that are not executed by the compiler or an interpreter.
It is considered to be a good practice to document our code using comments.
When and Why to use Comments in C programming?
1. A person reading a large code will be bemused if comments are not provided about details of
the program.
2. C Comments are a way to make a code more readable by providing more descriptions.
3. C Comments can include a description of an algorithm to make code understandable.
4. C Comments can be used to prevent the execution of some parts of the code.
Types of comments in C
In C there are two types of comments in C language:
 Single-line comment
 Multi-line comment
1. Single-line Comment in C
A single-line comment in C starts with (//) double forward slash. It extends till the end of the line
and we don’t need to specify its end.

// This is a single line comment

2. Multi-line Comment in C
The Multi-line comment in C starts with a forward slash and asterisk (/*) and ends with an
asterisk and forward slash (*/). Any text between /* and */ is treated as a comment and is ignored
by the compiler.
It can apply comments to multiple lines in the program.
/*Comment starts
continues
continues
.
.
.
Comment ends*/
Tokens in C
A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.
The tokens of C language can be classified into six types based on the functions they are used to
perform. The types of C tokens are as follows:

1. Keywords
The keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program. Since keywords are referred names for a
compiler, they can’t be used as variable names. You cannot redefine keywords. However, you
can specify the text to be substituted for keywords before compilation by using C pre-processor
directives. C language supports 32 keywords which are given below:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and arrays.
These are user-defined names consisting of an arbitrarily long sequence of letters and digits with
either a letter or the underscore (_) as a first character. Identifier names must differ in spelling and
case from any keywords. Once declared, we can use the identifier in later program statements to
refer to the associated value. A special identifier called a statement label can be used in goto
statements.
Rules for Naming Identifiers
Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore (_).
 They must consist of only letters, digits, or underscore. No other special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.
Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
For example,
 main: method name.
 a: variable name.
3. Constants
The constants refer to the variables with fixed values. They are like normal variables but with the
difference that their values cannot be modified in the program once they are defined. Constants
may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;
const int* const ptr = &c_var;

4. Strings
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double quotes. Whereas, a
character is enclosed in single quotes in C and C++.
Examples of String
char string [20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘\
0’};
char string [20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;

5. C Token – Special Symbols


The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose. Some of these are listed below:
 Brackets []: Opening and closing brackets are used as array element references. These
indicate single and multidimensional subscripts.
 Parentheses (): Special symbols used to indicate function calls and function parameters.
 Braces {}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
 Comma (,): Used to separate more than one statement like for separating parameters in
function calls.
 Colon (:): It is an operator that essentially invokes something called an initialization list.
 Semicolon (;): It is known as a statement terminator. It indicates the end of one logical entity.
That’s why each individual statement must be ended with a semicolon.
 Asterisk (*): Used to create a pointer variable and for the multiplication of variables.
 Assignment operator (=): Used to assign values and for logical operation validation.
 Pre-processor (#): The pre-processor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
 Period (.): Used to access members of a structure or union.
 Tilde (~): Used as a destructor to free some space from memory.

6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and other objects. The
data items on which operators act are called operands.
Depending on number of operands, upon that an operator can act, are classified as follows:
 Unary Operators: Operators that require only a single operand to act upon.
For Example, increment and decrement operators
 Binary Operators : Operators that require two operands to act upon.
Binary operators can further be classified into:
1. Arithmetic operators 2. Relational Operators 3. Logical Operators
4. Assignment Operators 5. Bitwise Operator
 Ternary Operator : Operator that requires three operands to act upon.
Conditional Operator(?) is also called the ternary operator.
Variable in C?

A variable in C language is the name associated with some memory location to store data of
different types that helps a programmer to store, access, manipulate and retrieves different types
of data when required. A variable is the basic building block of a C program that can be used in
expressions as a substitute in place of the value it stores.
We can store in the variable and reuse the same variable for storing some other data any number
of times.
There are many types of variables in C depending on the scope, storage class, lifetime, type of
data they store, etc. The size of the variable depends upon the data type it stores.

C Variable Syntax
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable

 data_type: Type of data that a variable can store.


 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.

Example
int var; // integer variable
char a; // character variable
float fff; // float variables

There are 3 aspects of defining a variable:

1. Variable Declaration
2. Variable Definition
3. Variable Initialization

1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the given
name and data type. No memory is allocated to a variable in the declaration.
2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it. A
defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;
Note: Most of the modern C compilers declare and define the variable in single step. Although
we can declare a variable in C by using extern keyword, it is not required in most of the cases. To
know more about variable declaration and definition, click here.
3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the
variable.
Example
int var; // variable definition
var = 10; // initialization
or
int var = 10; // variable declaration and definition

How to use variables in C?


The below example demonstrates how the use variables in C language.

// C program to demonstrate the


// declaration, definition and
// initialization
#include <stdio.h>
int main ()
{
// declaration with definition
int defined_var;

printf ("Defined_var: %d\n", defined_var);

// initialization
defined_var = 12;

// declaration + definition + initialization


int ini_var = 25;

printf ("Value of defined_var after initialization: %d\n",defined_var);


printf ("Value of ini_var: %d", ini_var);

return 0;
}

Output
Defined_var: 0
Value of defined_var after initialization: 12
Value of ini_var: 25
Rules for Naming Variables in C
You can assign any name to the variable as long as it follows the following rules:
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot start with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword.

C Variable Types
The C variables can be classified into the following types:
1. Local Variables 2. Global Variables
3. Static Variables 4. Automatic Variables
5. Extern Variables 6. Register Variables
1. Local Variables in C
A Local variable in C is a variable that is declared inside a function or a block of code. Its scope
is limited to the block or function in which it is declared.

Example of Local Variable in C

// C program to declare and print local variable inside a


// function.
#include <stdio.h>

void function ()
{
int x = 10; // local variable
printf ("%d", x);
}

int main ()
{
function ();
}

Output
10
In the above code, x can be used only in the scope of function (). Using it in the main function
will give an error.
2. Global Variables in C
A Global variable in C is a variable that is declared outside the function or a block of code. Its
scope is the whole program i.e. we can access the global variable anywhere in the C program after
it is declared.

Example of Global Variable in C

// C program to demonstrate use of global variable


#include <stdio.h>

int x = 20; // global variable

void function1() {printf ("Function 1: %d\n", x);}

void function2() {printf ("Function 2: %d\n", x);}

int main ()
{

function1();
function2();
return 0;
}

Output
Function 1: 20
Function 2: 20
In the above code, both functions can use the global variable as global variables are accessible by
all the functions.
Note: When we have same name for local and global variable, local variable will be given
preference over the global variable by the compiler.
For accessing global variable in this case, we can use the method mention here.

3. Static Variables in C
A static variable in C is a variable that is defined using the static keyword. It can be defined
only once in a C program and its scope depends upon the region where it is declared (can
be global or local).
The default value of static variables is zero.

Syntax of Static Variable in C


static data_type variable_name = initial_value;
As its lifetime is till the end of the program, it can retain its value for multiple function calls as
shown in the example.

Example of Static Variable in C


// C program to demonstrate use of static variable
#include <stdio.h>
void function ()
{
int x = 20; // local variable
static int y = 30; // static variable
x = x + 10;
y = y + 10;
printf ("\tLocal: %d\n\tStatic: %d\n", x, y);
}

int main ()
{
printf ("First Call\n");
function ();
printf ("Second Call\n");
function ();
printf ("Third Call\n");
function ();
return 0;
}

Output
First Call
Local: 30
Static: 40
Second Call
Local: 30
Static: 50
Third Call
Local: 30
Static: 60
In the above example, we can see that the local variable will always print the same value
whenever the function will be called whereas the static variable will print the incremented value
in each function call.
Note: Storage Classes in C is the concept that helps us to determine the scope, lifetime, memory
location, and default value (initial value) of a variable.

4. Automatic Variable in C
All the local variables are automatic variables by default. They are also known as auto variables.
Their scope is local and their lifetime is till the end of the block. If we need, we can use
the auto keyword to define the auto variables.
The default value of the auto variables is a garbage value.

Syntax of Auto Variable in C

auto data_type variable_name;


or
data_type variable_name; (in local scope)

Example of auto Variable in C

// C program to demonstrate use of automatic variable


#include <stdio.h>

void function ()
{
int x = 10; // local variable (also automatic)
auto int y = 20; // automatic variable
printf ("Auto Variable: %d", y);
}
int main ()
{

Function ();
return 0;
}

Output
Auto Variable: 20
In the above example, both x and y are automatic variables. The only difference is that variable y
is explicitly declared with the auto keyword.

5. External Variables in C
External variables in C can be shared between multiple C files. We can declare an external
variable using the extern keyword. Their scope is global and they exist between multiple C files.

Syntax of Extern Variables in C

extern data_type variable_name;

Example of Extern Variable in C

----------myfile.h------------
extern int x=10; //external variable (also global)

----------program1.c----------
#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf ("Global variable: %d", x);
}
In the above example, x is an external variable that is used in multiple C files.
6. Register Variables in C
Register variables in C are those variables that are stored in the CPU register instead of the
conventional storage place like RAM. Their scope is local and exists till the end of the block or a
function.
These variables are declared using the register keyword. The default value of register variables is
a garbage value.

Syntax of Register Variables in C

register data_type variable_name = initial_value;


Example of Register Variables in C
// C program to demonstrate the definition of register
// variable
#include <stdio.h>

int main ()
{
// register variable
register int var = 22;

printf ("Value of Register Variable: %d\n", var);


return 0;
}

Output
Value of Register Variable: 22
NOTE: We cannot get the address of the register variable using addressof (&) operator because
they are stored in the CPU register. The compiler will throw an error if we try to get the address
of register variable.

Constant Variable in C
Till now we have only seen the variables whose values can be modified any number of times. But
C language also provides us a way to make the value of a variable immutable. We can do that by
defining the variable as constant.
A constant variable in C is a read-only variable whose value cannot be modified once it is
defined. We can declare a constant variable using the const keyword.

Syntax of Const Variable in C

const data_type variable_name = value;


Note: We have to always initialize the const variable at the definition as we cannot modify its
value after defining.
Example of Const Variable in C

// C Program to Demonstrate constant variable


#include <stdio.h>

int main ()
{
// variable
int not_constant;

// constant variable;
const int constant = 20;

// changing values
not_constant = 40;
constant = 22;

return 0;
}

Output

FAQs on C Variables
Q1. What is the difference between variable declaration and definition in C?

Ans:
In variable declaration, only the name and type of the variable is specified but no memory is
allocated to the variable.
In variable definition, the memory is also allocated to the declared variable.

Q2. What is the variable’s scope?

Ans:
The scope of a variable is the region in which the variable exists and it is valid to perform
operations on it. Beyond the scope of the variable, we cannot access it and it is said to be out of
scope.
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can
store like integer, character, floating, double, etc. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. The data type is a
collection of data with values having fixed values, meaning as well as its characteristics.
The data types in C can be classified as follows:

Types Description

Primitive data types are the most basic data types that are used for
Primitive Data Types
representing simple values such as integers, float, characters, etc.

User Defined Data Types The user-defined data types are defined by the user himself.

The data types that are derived from the primitive or built-in
Derived Types
datatypes are referred to as Derived Data Types.

Different data types also have different ranges up to which they can store numbers. These ranges
may vary from compiler to compiler. Below is a list of ranges along with the memory requirement
and format specifiers on the 32-bit GCC compiler.
Size Format
Data Type (bytes) Range Specifier

short int 2 -32,768 to 32,767 %hd

unsigned short int 2 0 to 65,535 %hu

unsigned int 4 0 to 4,294,967,295 %u

int 4 -2,147,483,648 to 2,147,483,647 %d

long int 4 -2,147,483,648 to 2,147,483,647 %ld

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

long long int 8 -(2^63) to (2^63)-1 %lld

unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu

signed char 1 -128 to 127 %c

unsigned char 1 0 to 255 %c

float 4 1.2E-38 to 3.4E+38 %f

double 8 1.7E-308 to 1.7E+308 %lf

long double 16 3.4E-4932 to 1.1E+4932 %Lf

Note: The long, short, signed and unsigned are datatype modifier that can be used with some
primitive data types to change the size or length of the datatype.
The following are some main primitive data types in C:

Integer Data Type


The integer datatype in C is used to store the whole numbers without decimal values. Octal values,
hexadecimal values, and decimal values can be stored in int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d

Syntax of Integer
We use int keyword to declare the integer variable:
int var_name;
The integer data type can also be used as
1. unsigned int: Unsigned int data type in C is used to store the data values from zero to positive
numbers but it can’t store negative values like signed int.
2. short int: It is lesser in size than the int by 2 bytes so can only store values from –32,768 to
32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Note: The size of an integer data type is compiler-dependent. We can use sizeof operator to check
the actual size of any data type.

Example of int
// C program to print Integer data types.
#include <stdio.h>

int main ()
{
int a = 9; // Integer value with positive data.
int b = -9; // integer value with negative data.
int c = 89U; // U or u is Used for Unsigned int in C.
long int d = 99998L; // L or l is used for long int in C.

printf ("Integer value with positive data: %d\n", a);


printf ("Integer value with negative data: %d\n", b);
printf ("Integer value with an unsigned int data: %u\n", c);
printf ("Integer value with a long int data: %ld", d);
return 0;
}

Output
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998

Character Data Type


Character data type allows its variable to store only a single character. The size of the character is 1
byte. It is the most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c
Syntax of char
The char keyword is used to declare the variable of character type:
char var_name;

Example of char

// C program to print Integer data types.


#include <stdio.h>

int main ()
{
char a = 'a';
char c;
printf ("Value of a: %c\n", a);
a++;
printf ("Value of a after increment is: %c\n", a);

// c is assigned ASCII values which corresponds to the character 'c'


// a-->97 b-->98 c-->99
// here c will be printed
c = 99;

printf ("Value of c: %c", c);


return 0;
}

Output
Value of a: a
Value of a after increment is: b
Value of c: c

Float Data Type


In C programming float data type is used to store floating-point values. Float in C is used to store
decimal and exponential values. It is used to store decimal numbers (numbers with floating point
values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f

Syntax of float
The float keyword is used to declare the variable as a floating point:
float var_name;

Example of Float
// C Program to demonstrate use
// of Floating types
#include <stdio.h>

int main ()
{
float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf ("%f\n", a);
printf ("%f\n", b);
printf ("%f", c);
return 0;
}

Output
9.000000
2.500000
0.000200

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point values) with
double precision. It is used to define numeric values which hold numbers with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding 64 bits of
decimal numbers or floating points. Since double has more precision as compared to that float then
it is much more obvious that it occupies twice the memory occupied by the floating-point type. It
can easily accommodate about 16 to 17 digits after or before a decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf

Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;

Example of Double
// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main ()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf ("%lf\n", a);


printf ("%lf\n", b);
printf ("%lf", c);
return 0;
}

Output
123123123.000000
12.293123
2312312312.123123

Void Data Type


The void data type in C is used to specify that no value is present. It does not provide a result value
to its caller. It has no values and no operations. It is used to represent nothing. Void is used in
multiple ways as function return type, function arguments as void, and pointers to void.

Syntax:
// function return type void
void exit (int check);

// Function without any parameter can accept void.

int print(void);

// memory allocation function which


// returns a pointer to void.
void *malloc (size_t size);

Example of Void
// C program to demonstrate
// use of void pointers
#include <stdio.h>

int main ()
{
int val = 30;
void* ptr = &val;
printf ("%d", *(int*) ptr);
return 0;
}

Output

30

Size of Data Types in C


The size of the data types in C is dependent on the size of the architecture, so we cannot define the
universal size of the data types. For that, the C language provides the sizeof () operator to check the
size of the data types.

Example
// C Program to print size of
// different data type in C
#include <stdio.h>

int main ()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);
printf ("The size of int data type: %d\n", size_of_int);
printf ("The size of char data type: %d\n",
size_of_char);
printf ("The size of float data type: %d\n",
size_of_float);
printf ("The size of double data type: %d",
size_of_double);

return 0;
}

Output
The size of int data type: 4
The size of char data type: 1
The size of float data type: 4
The size of double data type: 8
Operators in C

What are Operators in C?


C Operators are symbols that represent operations to be performed on one or more operands. C
provides a wide range of operators, which can be classified into different categories based on their
functionality. Operators are used for performing operations on variables and values.
For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;

Types of Operators in C
C has many built-in operators and can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

Operators in C

The above operators have been discussed in detail:


1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %, ++, --).
Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example: Increment
(++) and Decrement (--) Operators
int val = 5;
cout<<++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators in C
These are used for the comparison of the values of two operands. For example, checking if one
operand is equal to the other operand or not, whether an operand is greater than the other operand or
not, etc. Some of the relational operators are (= =, >=, <=).

int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b
3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.
For example, the logical AND represented as the ‘&&’ operator in C returns true when both the
conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns
true when both a and b are true (i.e. non-zero).

cout<< ((4 != 5) && (4 < 5)); // true


4. Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The operators are
first converted to bit-level and then the calculation is performed on the operands. Mathematical
operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing. For example, the bitwise AND operator represented as ‘&’ in C takes two
numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if
both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right-side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the compiler
will raise an error.
Different types of assignment operators are shown below:
a) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right to the
variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the
right from the current value of the variable on left and then assigns the result to the variable on the
left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the variable on
the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators
Apart from the above operators, there are some other operators available in C used to perform some
specific tasks. Some of them are discussed here:
i. sizeof operator
 a compile-time unary operator which can be used to compute the size of its operand (variable).
 result of sizeof is of the unsigned integral type which is usually denoted by size_t.
ii. Comma Operator
 The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value (and
type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
iii. Conditional Operator
 The conditional operator is of the form Expression1? Expression2: Expression3
 Here, Expression1 is the condition to be evaluated. If the condition (Expression1) is True then
we will execute and return the result of Expression2 otherwise if the condition (Expression1)
is false then we will execute and return the result of Expression3.
 We may replace the use of if..else statements with conditional operators.
iv. dot (.) and arrow (->) Operators
 Member operators are used to referencing individual members of classes, structures, and unions.
 The dot operator is applied to the actual object.
 The arrow operator is used with a pointer to an object.
v. Cast Operator
 Casting operators convert one data type to another. For example, int (2.2000) would return 2.
 A cast is a special operator that forces one data type to be converted into another.
 The most general cast supported by most of the C compilers is as follows − [ (type)
expression ].
To know more about the topic refer to this article.
vi. &,* Operator
 Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
 The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
C Operators with Example

// C Program to Demonstrate the working concept of


// Operators
#include <stdio.h>

int main ()
{
int a = 10, b = 5;
// Arithmetic operators
printf ("Following are the Arithmetic operators in C\n");
printf ("The value of a + b is %d\n", a + b);
printf ("The value of a - b is %d\n", a - b);
printf ("The value of a * b is %d\n", a * b);
printf ("The value of a / b is %d\n", a / b);
printf ("The value of a % b is %d\n", a % b);

// First print (a) and then increment it by 1


printf ("The value of a++ is %d\n", a++);

// First print (a+1) and then decrease it by 1


printf ("The value of a-- is %d\n", a--);

// Increment (a) by (a+1) and then print


printf ("The value of ++a is %d\n", ++a);

// Decrement (a+1) by (a) and then print


printf ("The value of --a is %d\n", --a);

// Assignment Operators --> used to assign values to


// variables int a =3, b=9; char d='d';
// Comparison operators
// Output of all these comparison operators will be (1)
// if it is true and (0) if it is false
printf (
"\nFollowing are the comparison operators in C\n");
printf ("The value of a == b is %d\n", (a == b));
printf ("The value of a != b is %d\n", (a != b));
printf ("The value of a >= b is %d\n", (a >= b));
printf ("The value of a <= b is %d\n", (a <= b));
printf ("The value of a > b is %d\n", (a > b));
printf ("The value of a < b is %d\n", (a < b));

// Logical operators
printf ("\nFollowing are the logical operators in C\n");
printf ("The value of this logical and operator ((a==b) "
"&& (a<b)) is:%d\n",
((a == b) && (a < b)));
printf ("The value of this logical or operator ((a==b) "
"|| (a<b)) is:%d\n",
((a == b) || (a < b)));
printf ("The value of this logical not operator "
"(!(a==b)) is:%d\n",
(!(a == b)));

return 0;
}

Output
Following are the Arithmetic operators in C
The value of a + b is 15
The value of a - b is 5
The value of a * b is 50
The value of a / b is 2
The value of a % b is 0
The value of a++ is 10
The value of a-- is 11
The value of ++a is 11
The value of --a is 10

Following are the comparison operators in C


The value of a == b is 0
The value of a != b is 1
The value of a >= b is 1
The value of a <= b is 0
The value of a > b is 1
The value of a < b is 0

Following are the logical operators in C


The value of this logical and operator ((a==b) && (a<b)) is:0
The value of this logical or operator ((a==b) || (a<b)) is:0
The value of this logical not operator (!(a==b)) is:1
Precedence of Operators in C
The below table describes the precedence order and associativity of
operators in C. The precedence of the operator decreases from top to
bottom.

Precedenc
e Operator Description Associativity

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

1 . Member selection via object name left-to-right

-> Member selection via a pointer left-to-right

a++/a– Postfix increment/decrement (a is a variable) left-to-right

++a/–a Prefix increment/decrement (a is a variable) right-to-left

+/- Unary plus/minus right-to-left

!~ Logical negation/bitwise complement right-to-left

Cast (convert value to temporary value of


(type) right-to-left
2 type)

* Dereference right-to-left

& Address (of operand) right-to-left

Determine size in bytes on this


sizeof right-to-left
implementation

3 *,/,% Multiplication/division/modulus left-to-right

4 +/- Addition/subtraction left-to-right


Precedenc
e Operator Description Associativity

5 << , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right

6
Relational greater than/greater than or equal
> , >= left-to-right
to

7 == , != Relational is equal to/is not equal to left-to-right

8 & Bitwise AND left-to-right

9 ^ Bitwise exclusive OR left-to-right

10 | Bitwise inclusive OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

14 = Assignment right-to-left

+= , -= Addition/subtraction assignment right-to-left

*= , /= Multiplication/division assignment right-to-left

%= , &= Modulus/bitwise AND assignment right-to-left

^= , |= Bitwise exclusive/inclusive OR assignment right-to-left


Precedenc
e Operator Description Associativity

<>= Bitwise shift left/right assignment right-to-left

15 , expression separator left-to-right

Conclusion
In this article, the points we learned about the operator are as follows:
 Operators are symbols used for performing some kind of operation in
C.
 The operation can be mathematical, logical, relational, bitwise,
conditional, or logical.
 There are seven types of Unary operators, Arithmetic operator,
Relational operator, Logical operator, Bitwise operator, Assignment
operator, and Conditional operator.
 Every operator returns a numerical value except logical and
conditional operator which returns a boolean value(true or false).
 ‘=’ and ‘==’ are not same as ‘=’ assigns the value whereas ‘==’
checks if both the values are equal or not.
 There is a Precedence in the operator means the priority of using one
operator is greater than another operator.
Frequently Asked Questions(FAQs)
1. What are operators in C?
Operators in C are certain symbols in C used for performing certain
mathematical, relational, bitwise, conditional, or logical operations for
the user.
2. What are the 7 types of operators in C?
There are 7 types of operators in C as mentioned below:
 Unary operator
 Arithmetic operator
 Relational operator
 Logical operator
 Bitwise operator
 Assignment operator
 Conditional operator
3. What is the difference between the ‘=’ and ‘==’ operators?
‘=’ is a type of assignment operator that places the value in right to the
variable on left, Whereas ‘==’ is a type of relational operator that is used
to compare two elements if the elements are equal or not.
4. What is the difference between prefix and postfix operators in C?
Prefix operations are the operations in which the value is returned prior
to the operation whereas in postfix operations value is returned after
updating the value in the variable.
Example:
b=c=10;
a=b++; // a==10
a=++c; // a==11
5. What is the Modulo operator?
The Modulo operator(%) is used to find the remainder if one element is
divided by another.
Example:
a % b (a divided by b)
5 % 2 == 1
Arithmetic Operators in C


Arithmetic Operators are the type of operators in C that are used to


perform mathematical operations in a C program. They can be used in
programs to define expressions and mathematical formulas.
What are C Arithmetic Operators?
The C arithmetic operators are the symbols that are used to perform
mathematical operations on operands. There are a total of 9 arithmetic
operators in C to provide the basic arithmetic operations such as
addition, subtraction, multiplication, etc.

Types of Arithmetic Operators in C


The C Arithmetic Operators are of two types based on the number of
operands they work. These are as follows:
1. Binary Arithmetic Operators
2. Unary Arithmetic Operators
1. Binary Arithmetic Operators in C
The C binary arithmetic operators operate or work on two operands. C
provides 5 Binary Arithmetic Operators for performing arithmetic
functions which are as follows:

Operato Name of the


r Operator Arithmetic Operation Syntax

+ Addition Add two operands. x+y


Operato Name of the
r Operator Arithmetic Operation Syntax

Subtract the second operand from the first


– Subtraction x–y
operand.

* Multiplication Multiply two operands. x*y

Divide the first operand by the second


/ Division x/y
operand.

Calculate the remainder when the first


% Modulus operand is divided by the second operand. x%y

Example of Binary Arithmetic Operator in C

// C program to demonstrate syntax of binary arithmetic

// operators

#include <stdio.h>

int main()

int a = 10, b = 4, res;

// printing a and b

printf("a is %d and b is %d\n", a, b);


res = a + b; // addition

printf("a + b is %d\n", res);

res = a - b; // subtraction

printf("a - b is %d\n", res);

res = a * b; // multiplication

printf("a * b is %d\n", res);

res = a / b; // division

printf("a / b is %d\n", res);

res = a % b; // modulus

printf("a %% b is %d\n", res);

return 0;

Output
a is 10 and b is 4
a + b is 14
a - b is 6
a * b is 40
a / b is 2
a % b is 2

2. Unary Arithmetic Operators in C


The unary arithmetic operators operate or work with a single operand. In
C, we have two unary arithmetic operators which are as follows:

Operator Symbol Operation Implementation

Decrement Decreases the integer value of the


— –h or h–
Operator variable by one.

Increment Increases the integer value of the


++ ++h or h++
Operator variable by one.

Unary Plus
+ Returns the value of its operand. +h
Operator

Unary Minus Returns the negative of the value of


– -h
Operator its operand.

Increment Operator in C

The ‘++’ operator is used to increment the value of an integer. It can be


used in two ways:
1. Pre-Increment
When placed before the variable name (also called the pre-
increment operator), its value is incremented instantly. Consider the
example:
a = ++x;
This example can be expanded to
a = (x = x + 1);
2. Post Increment
When it is placed after the variable name (also called post-
increment operator), its value is preserved temporarily until the
execution of this statement and it gets updated before the execution of
the next statement. For example:
a = x++;
It can be expanded to
a = x;
x = x + 1;
Decrement Operator in C

The ‘–‘ operator is used to decrement the value of an integer. Just like
the increment operator, the decrement operator can also be used in two
ways:
1. Pre-Decrement
When placed before the variable name (also called the pre-
decrement operator), its value is decremented instantly. For example, –
– x.
2. Post Decrement
When it is placed after the variable name (also called post-
decrement operator), its value is preserved temporarily until the
execution of this statement and it gets updated before the execution of
the next statement. For example, x – –.

Example of Unary Operators in C

// C program to demonstrate working

// of Unary arithmetic

// operators

#include <stdio.h>

int main()

int a = 10, b = 4, res;

printf("Post Increment and Decrement\n");

// post-increment example:

// res is assigned 10 only, a is not updated yet

res = a++;
printf("a is %d and result is %d\n", a,

res); // a becomes 11 now

// post-decrement example:

// res is assigned 11 only, a is not updated yet

res = a--;

printf("a is %d and result is %d\n", a,

res); // a becomes 10 now

printf("\nPre Increment and Decrement\n");

// pre-increment example:

// res is assigned 11 now since

// a is updated here itself

res = ++a;

// a and res have same values = 11

printf("a is %d and result is %d\n", a, res);

// pre-decrement example:

// res is assigned 10 only since a is updated here

// itself

res = --a;
// a and res have same values = 10

printf("a is %d and result is %d\n", a, res);

return 0;

Output
Post Increment and Decrement
a is 11 and result is 10
a is 10 and result is 11

Pre Increment and Decrement


a is 11 and result is 11
a is 10 and result is 10

Multiple Operators in a Single Expression


Till now, we have only seen expressions in which we have used a single
operator in a single expression. What happens when we use multiple
operators in a single expression? Let’s try to understand this with the
help of the below example.

Example

// C program to demonstrate the use

#include <stdio.h>

int main()
{

int var;

// expression with multiple operators

var = 10 * 20 + 15 / 5;

printf("Result = %d", var);

return 0;

Output
Result = 203
Explanation: The order of evaluation of the given expression is : ( ( 10
* 20 ) + (15 / 5 ) ).
This is due to the Operator Precedence and Associativity concept in
C language where the operators with higher precedence will be
evaluated first. The operator precedence system helps to provide
unambiguously expressions.
Examples of C Arithmetic Operators
Example 1: C Program to find the area of a rectangle and triangle.

We will use the arithmetic operators for calculating the area and
perimeter of the rectangle using the standard formula of each.

// C Program to calculate the area and perimeter of the

// rectangle

#include <stdio.h>
int main()

// declaring dimensions of the rectangle

int length = 10;

int breadth = 5;

// declaring variables to store the results

int area, perimeter;

// calculating area

area = length * breadth;

// calculating perimeter

perimeter = 2 * (length + breadth);

// printing results

printf("Area = %d\nPerimeter = %d", area, perimeter);

return 0;

Output
Area = 50
Perimeter = 30

Conclusion
In this article, we discussed the arithmetic operators in C and how they
are useful in performing both basic and complex calculations in the C
program. These are one of the core concepts that build the foundation of
the C language.

FAQs on C Arithmetic Operators


1. List all the arithmetic operators in C.

Below is the list of all the arithmetic operators in C language:


 ( + ) Addition Operator
 ( – ) Subtraction Operator
 ( * ) Multiplication Operator
 ( / ) Division Operator
 ( % ) Modulo Operator
 ( ++ ) Increment Operator
 ( — ) Decrement Operator
 ( + ) Unary Plus Operator
 ( – ) Unary Minus Operator

2. What is the difference between the unary minus and subtraction


operators?

Although the unary minus and subtraction operator looks the same, their
function is different from each other in the following ways:
 As the name suggests, the unary operator works on a single operator
while the subtraction operator is a binary operator that works on two
operands.
 The unary minus returns the negative of the value of its operand while
the subtraction operator returns the difference between its two
operands.
Unary operators in C/C++


Unary operators are the operators that perform operations on a single


operand to produce a new value.
Types of unary operators
Types of unary operators are mentioned below:
1. Unary minus ( – )
2. Increment ( ++ )
3. Decrement ( — )
4. NOT ( ! )
5. Addressof operator ( & )
6. sizeof()
1. Unary Minus
The minus operator ( – ) changes the sign of its argument. A positive
number becomes negative, and a negative number becomes positive.
int a = 10;
int b = -a; // b = -10
Unary minus is different from the subtraction operator, as subtraction
requires two operands.
Below is the implementation of the unary minus (-) operator:

// C Program to illustrate the use of 'unary minus operator'

#include <stdio.h>

int main()

// declaring a positive integer

int positiveInteger = 100;

// using - sign to make the value of positive integers

// to negative

int negativeInteger = -positiveInteger;

printf("Positive Integer = %d\n", positiveInteger);

printf("Negative Integer = %d", negativeInteger);

return 0;

Output
Positive Integer = 100
Negative Integer = -100
2. Increment
The increment operator ( ++ ) is used to increment the value of the
variable by 1. The increment can be done in two ways:
2.1 prefix increment
In this method, the operator precedes the operand (e.g., ++a). The value
of the operand will be altered before it is used.
Example:
int a = 1;
int b = ++a; // b = 2
2.2 postfix increment
In this method, the operator follows the operand (e.g., a++). The value
operand will be altered after it is used.
Example:
int a = 1;
int b = a++; // b = 1
int c = a; // c = 2
Below is the implementation of the increment ( ++ ):
 C
 C++

// C program to illustrate increment

#include <stdio.h>

int main()

int a = 5;

int b = 5;

printf("Pre-Incrementing a = %d\n", ++a);

printf("Post-Incrementing b = %d", b++);

return 0;

Output
Pre-Incrementing a = 6
Post-Incrementing b = 5
3. Decrement
The decrement operator ( — ) is used to decrement the value of the
variable by 1. The decrement can be done in two ways:
3.1 prefix decrement
In this method, the operator precedes the operand (e.g., – -a). The value
of the operand will be altered before it is used.
Example:
int a = 1;
int b = --a; // b = 0
3.2 postfix decrement
In this method, the operator follows the operand (e.g., a- -). The value of
the operand will be altered after it is used.
Example:
int a = 1;
int b = a--; // b = 1
int c = a; // c = 0
Below is the implementation of the increment ( ++ ):
 C
 C++

// C program to illustrate decrement

#include <stdio.h>

int main()

int a = 5;

int b = 5;

printf("Pre-Decrementing a = %d\n", --a);

printf("Post-Decrementing b = %d", b--);

return 0;
}

Output
Pre-Decrementing a = 4
Post-Decrementing b = 5
4. NOT ( ! )
The logical NOT operator ( ! ) is used to reverse the logical state of its
operand. If a condition is true, then the Logical NOT operator will make it
false.
Example:
If x is true, then !x is false
If x is false, then !x is true
Below is the implementation of the NOT (!) operator:
 C
 C++

// C program to illustrate NOT operator

#include <stdio.h>

int main()

int a = 10;

int b = 5;

if (!(a > b))

printf("b is greater than a\n");

else
printf("a is greater than b");

return 0;

Output
a is greater than b
5. Addressof operator ( & )
The addressof operator ( & ) gives an address of a variable. It is used
to return the memory address of a variable. These addresses returned by
the address-of operator are known as pointers because they “point” to
the variable in memory.
Example:
& gives an address on variable n
int a;
int *ptr;
ptr = &a; // address of a is copied to the location ptr.
Below is the implementation of the Addressof operator(&):
 C
 C++

// C program to demonstrate the use of 'address-of(&)'

// operator

#include <stdio.h>

int main()

int a = 20;
printf("Address of a = %p", &a);

return 0;

Output
0x7ffddcf0c8ec
6. sizeof()
This operator returns the size of its operand, in bytes.
The sizeof() operator always precedes its operand. The operand is an
expression, or it may be a cast.
Note: The `sizeof()` operator in C++ is machine dependent. For
example, the size of an ‘int’ in C++ may be 4 bytes in a 32-bit machine
but it may be 8 bytes in a 64-bit machine.
Below is the implementation of sizeof() operator:
 C
 C++

// C program to illustrate the sizeof operator

#include <stdio.h>

int main()

// printing the size of double and int using sizeof

printf("Size of double: %d\n", sizeof(double));

printf("Size of int: %d\n", sizeof(int));

return 0;
}

Output
Size of double: 8
Size of int: 4

Operators in C | Set 2 (Relational and Logical Operators)


 Read

 Discuss

 Courses

 Practice



We have discussed Introduction to Operators in C where we got an


overall idea of what types of Operators, C and C++ support, and its basic
implementations. Following that, we studied Arithmetic
Operators where we got a detailed understanding of the types and use
of Arithmetic operators in C and C++. In this article, let’s try to
understand the types and uses of Relational and Logical Operators.
Relational Operators
Relational operators are used for the comparison of two values to understand the type of
relationship a pair of number shares. For example, less than, greater than, equal to, etc. Let’s see
them one by one

1. Equal to operator: Represented as ‘==’, the equal to operator checks whether the two given
operands are equal or not. If so, it returns true. Otherwise, it returns false. For
example, 5==5 will return true.
2. Not equal to operator: Represented as ‘!=’, the not equal to operator checks whether the two
given operands are equal or not. If not, it returns true. Otherwise, it returns false. It is the exact
boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
3. Greater than operator: Represented as ‘>’, the greater than operator checks whether the first
operand is greater than the second operand or not. If so, it returns true. Otherwise, it returns
false. For example, 6>5 will return true.
4. Less than operator: Represented as ‘<‘, the less than operator checks whether the first operand is
lesser than the second operand. If so, it returns true. Otherwise, it returns false. For
example, 6<5 will return false.
5. Greater than or equal to operator: Represented as ‘>=’, the greater than or equal to operator
checks whether the first operand is greater than or equal to the second operand. If so, it returns
true else it returns false. For example, 5>=5 will return true.
6. Less than or equal to operator: Represented as ‘<=’, the less than or equal to operator checks
whether the first operand is less than or equal to the second operand. If so, it returns true else
false. For example, 5<=5 will also return true.
Examples:
// C program to demonstrate working of relational operators
#include <stdio.h>

int main()
{
int a = 10, b = 4;

// greater than example


if (a > b)
printf("a is greater than b\n");
else
printf("a is less than or equal to b\n");

// greater than equal to


if (a >= b)
printf("a is greater than or equal to b\n");
else
printf("a is lesser than b\n");

// less than example


if (a < b)
printf("a is less than b\n");
else
printf("a is greater than or equal to b\n");

// lesser than equal to


if (a <= b)
printf("a is lesser than or equal to b\n");
else
printf("a is greater than b\n");

// equal to
if (a == b)
printf("a is equal to b\n");
else
printf("a and b are not equal\n");

// not equal to
if (a != b)
printf("a is not equal to b\n");
else
printf("a is equal b\n");

return 0;
}

Output:
a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b

Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of
the original condition under consideration. They are described below:

1. Logical AND operator: The ‘&&’ operator returns true when both the conditions under
consideration are satisfied. Otherwise, it returns false. For example, a && b returns true when
both a and b are true (i.e. non-zero).
2. Logical OR operator: The ‘||’ operator returns true even if one (or both) of the conditions
under consideration is satisfied. Otherwise, it returns false. For example, a || b returns true if one
of a or b, or both are true (i.e. non-zero). Of course, it returns true when both a and b are true.
3. Logical NOT operator: The ‘!’ operator returns true the condition in consideration is not
satisfied. Otherwise, it returns false. For example, !a returns true if a is false, i.e. when a=0.
Examples:

// C program to demonstrate working of logical operators


#include <stdio.h>

int main()
{
int a = 10, b = 4, c = 10, d = 20;

// logical operators

// logical AND example


if (a > b && c == d)
printf("a is greater than b AND c is equal to d\n");
else
printf("AND condition not satisfied\n");

// logical OR example
if (a > b || c == d)
printf("a is greater than b OR c is equal to d\n");
else
printf("Neither a is greater than b nor c is equal "
" to d\n");

// logical NOT example


if (!a)
printf("a is zero\n");
else
printf("a is not zero");

return 0;
}

Output:
AND condition not satisfied
a is greater than b OR c is equal to d
a is not zero
Time Complexity: O(1)
Auxiliary Space: O(1)
Short-Circuiting in Logical Operators:

 In the case of logical AND, the second operand is not evaluated if the first operand is false. For
example, program 1 below doesn’t print “GeeksQuiz” as the first operand of logical AND itself
is false.

#include <stdbool.h>

#include <stdio.h>

int main()

int a = 10, b = 4;

bool res = ((a == b) && printf("GeeksQuiz"));

return 0;

Output:
No Output

 But the below program prints “GeeksQuiz” as the first operand of logical AND is true.

#include <stdbool.h>

#include <stdio.h>

int main ()

int a = 10, b = 4;

bool res = ((a != b) && printf("GeeksQuiz"));


return 0;

Output
GeeksQuiz
 In the case of logical OR, the second operand is not evaluated if the first operand is true. For
example, program 1 below doesn’t print “GeeksQuiz” as the first operand of logical OR itself is
true.

#include <stdbool.h>
#include <stdio.h>
int main()
{
int a = 10, b = 4;
bool res = ((a != b) || printf("GeeksQuiz"));
return 0;
}

Output:
No Output

Time Complexity: O(1)


Auxiliary Space:O(1)
 But the below program prints “GeeksQuiz” as the first operand of
logical OR is false.

#include <stdbool.h>

#include <stdio.h>

int main()

int a = 10, b = 4;

bool res = ((a == b) || printf("GeeksQuiz"));

return 0;
}

Output
GeeksQuiz
Time Complexity: O(1)
Auxiliary Space: O(1)
Quiz on Operators in C
This article is contributed by Ayush Jaggi. Please write comments if you
find anything incorrect, or if you want to share more information about
the topic discussed above

Last Updated : 26 Feb, 2023

Bitwise Operators in C/C++


 Read

 Discuss

 Courses

 Practice

 Video



In C, the following 6 operators are bitwise operators (also known as bit


operators as they work at the bit-level). They are used to
perform bitwise operations in C.
1. The & (bitwise AND) in C or C++ takes two numbers as operands
and does AND on every bit of two numbers. The result of AND is 1 only
if both bits are 1.
2. The | (bitwise OR) in C or C++ takes two numbers as operands and
does OR on every bit of two numbers. The result of OR is 1 if any of
the two bits is 1.
3. The ^ (bitwise XOR) in C or C++ takes two numbers as operands
and does XOR on every bit of two numbers. The result of XOR is 1 if
the two bits are different.
4. The << (left shift) in C or C++ takes two numbers, the left shifts the
bits of the first operand, and the second operand decides the number
of places to shift.
5. The >> (right shift) in C or C++ takes two numbers, right shifts the
bits of the first operand, and the second operand decides the number
of places to shift.
6. The ~ (bitwise NOT) in C or C++ takes one number and inverts all
bits of it.

Let’s look at the truth table of the bitwise operators.


X Y X&Y X|Y X^Y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

Example of Bitwise Operators in C


The following program uses bitwise operators to perform bit operations in
C.

// C Program to demonstrate use of bitwise operators


#include <stdio.h>
int main()
{
// a = 5(00000101), b = 9(00001001)
unsigned char a = 5, b = 9;

// The result is 00000001


printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b);

// The result is 00001101


printf("a|b = %d\n", a | b);

// The result is 00001100


printf("a^b = %d\n", a ^ b);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

return 0;

Output
a = 5, b = 9
a & b = 1
a | b = 13
a ^ b = 12
~a = -6
b << 1 = 18

b >> 1 = 4
Interesting Facts About Bitwise Operators

1. The left-shift and right-shift operators should not be used for negative numbers.
If the second operand(which decides the number of shifts) is a negative number, it results in
undefined behavior in C. For example results of both 1 <<- 1 and 1 >> -1 is undefined. Also, if the
number is shifted more than the size of the integer, the behavior is undefined. For example, 1 << 33
is undefined if integers are stored using 32 bits. Another thing is NO shift operation is performed if
the additive expression (operand that decides no of shifts) is 0. See this for more details.
Note: In C++, this behavior is well-defined.

2. Interestingly!! The bitwise OR of two numbers is just the sum of those two numbers if there
is no carry involved, otherwise, you just add their bitwise AND.
Let’s say, we have a=5(101) and b=2(010), since there is no carry involved, their sum is just a|b.
Now, if we change ‘a’ to 6 which is 110 in binary, their sum would change to a|b + a&b since there
is a carry involved.

3. The bitwise XOR operator is the most useful operator from a technical interview
perspective.
It is used in many problems. A simple example could be “Given a set of numbers where all
elements occur an even number of times except one number, find the odd occurring number” This
problem can be efficiently solved by just doing XOR to all numbers.

#include <stdio.h>

// Function to return the only odd occurring element

int findOdd(int arr[], int n)

int res = 0, i;

for (i = 0; i < n; i++)

res ^= arr[i];

return res;
}

// Driver Method

int main(void)

int arr[] = { 12, 12, 14, 90, 14, 14, 14 };

int n = sizeof(arr) / sizeof(arr[0]);

printf("The odd occurring element is %d ",

findOdd(arr, n));

return 0;

Output
The odd occurring element is 90
4. The Bitwise operators should not be used in place of logical
operators.
The result of logical operators (&&, || and !) is either 0 or 1, but bitwise
operators return an integer value. 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 x = 2, y = 5;

(x & y) ? printf("True ") : printf("False ");

(x && y) ? printf("True ") : printf("False ");

return 0;

}
Output
False True
5. The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.
As mentioned in point 1, it works only if numbers are positive.

#include <stdio.h>

int main()

int x = 19;

printf("x << 1 = %d\n", x << 1);

printf("x >> 1 = %d\n", x >> 1);

return 0;

Output
x << 1 = 38
x >> 1 = 9
5. The & operator can be used to quickly check if a number is odd or even.
The value of the expression (x & 1) would be non-zero only if x is odd, otherwise, the value would
be zero.

#include <stdio.h>

int main()

int x = 19;

(x & 1) ? printf("Odd") : printf("Even");


return 0;

Output
Odd
6. The ~ operator should be used carefully.
The result of ~ operator on a small number can be a big number if the result is stored in an unsigned
variable. And the result may be a negative number if the result is stored in a signed variable
(assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the
sign bit)

// Note that the output of the following program is compiler dependent

#include <stdio.h>

int main()

unsigned int x = 1;

printf("Signed Result %d \n", ~x);

printf("Unsigned Result %ud \n", ~x);

return 0;

Output
Signed Result -2
Unsigned Result 4294967294

Logical operators in C are used to combine multiple conditions/constraints. Logical Operators


returns either 0 or 1, it depends on whether the expression result is true or false. In C programming
for decision-making, we use logical operators.
We have 3 logical operators in the C language:
 Logical AND ( && )
 Logical OR ( || )
 Logical NOT ( ! )

Types of Logical Operators


1. Logical AND Operator ( && )

If both operands are non zero then the condition becomes true.
Otherwise, the result has a value of 0. The return type of the result is int.
Below is the truth table for the logical AND operator.

X Y X && Y

1 1 1

1 0 0

0 1 0

0 0 0

Syntax
(operand_1 && operand_2)
Example
 C

// C program for Logical

// AND Operator

#include <stdio.h>

// Driver code

int main()

int a = 10, b = 20;

if (a > 0 && b > 0) {


printf("Both values are greater than 0\n");

else {

printf("Both values are less than 0\n");

return 0;

Output
Both values are greater than 0

2. Logical OR Operator ( || )

The condition becomes true if any one of them is non-zero. Otherwise, it


returns false i.e., 0 as the value. Below is the truth table for the logical
OR operator.

X Y X || Y

1 1 1

1 0 1

0 1 1

0 0 0

Syntax
(operand_1 || operand_2)
Example
 C

// C program for Logical


// OR Operator

#include <stdio.h>

// Driver code

int main()

int a = -1, b = 20;

if (a > 0 || b > 0) {

printf("Any one of the given value is "

"greater than 0\n");

else {

printf("Both values are less than 0\n");

return 0;

Output
Any one of the given value is greater than 0

3. Logical NOT Operator ( ! )

If the condition is true then the logical NOT operator will make it false
and vice-versa. Below is the truth table for the logical NOT operator.
X !X

0 1

1 0

Syntax
!(operand_1 && operand_2)
Example

// C program for Logical

// NOT Operator

#include <stdio.h>

// Driver code

int main()

int a = 10, b = 20;

if (!(a > 0 && b > 0)) {

// condition returned true but

// logical NOT operator changed

// it to false

printf("Both values are greater than 0\n");

else {
printf("Both values are less than 0\n");

return 0;

Short Circuit Logical Operators


When the result can be determined by evaluating the preceding Logical
expression without evaluating the further operands, it is known as short-
circuiting.
Short-circuiting can be seen in the equation having more than one
Logical operator. They can either AND, OR, or both.

1. Short Circuiting in Logical AND Operator

The logical AND operator returns true if and only if all operands evaluate
to true. If the first operand is false, then the further operands will not be
evaluated. This is because even if the further operands evaluate to true,
the entire condition will still return false.

Example

 C++

// C++ Program to illustrate short circuiting in Logical AND

#include <iostream>

using namespace std;

// utility function to check positive

bool is_positive(int number)

if (number > 0)
return true;

else

return false;

// utility function to check if the number is even

bool is_even(int number)

if (number % 2 == 0)

return true;

else

return false;

// driver code

int main()

int x = 10;

// Both conditions are evaluated

if (is_positive(x) && is_even(x)) {

cout << "Both conditions are satisfied." << endl;

}
else {

cout << "Conditions not satisfied." << endl;

int y = -5;

// The first condition is evaluated and found to be

// false, so the second condition is not evaluated

if (is_positive(y) && is_even(y)) {

cout << "Both conditions are satisfied." << endl;

else {

cout << "Conditions not satisfied." << endl;

return 0;

Output
Both conditions are satisfied.
Conditions not satisfied.

2. Short Circuiting in Logical OR Operator

OR operator returns true if at least one operand evaluates to true. If the


first operand is true, then the further operands will not be evaluated. This
is because even if the further operands evaluate to false, the entire
condition will still return true.
Example

 C++
// C++ program to illustrate the short circuiting in Logical
// OR
#include <iostream>
using namespace std;

// utility function to check positive number


bool is_positive(int number)
{
if (number > 0)
return true;
else
return false;
}

// utility function to check if the number is even


bool is_even(int number)
{
if (number % 2 == 0)
return true;
else
return false;
}

// driver code
int main()
{
int x = 8;

// The first condition is evaluated and found to be


// true, so the second condition is not evaluated
if (is_positive(x) || is_even(x)) {
cout << "At least one condition is satisfied."
<< endl;
}
else {
cout << "Conditions not satisfied." << endl;
}

int y = -5;

// The first condition is evaluated and found to be


// false, so the second condition is evaluated
if (is_positive(y) || is_even(y)) {
cout << "At least one condition is satisfied."
<< endl;
}
else {
cout << "Conditions not satisfied." << endl;
}

return 0;
}
Output
At least one condition is satisfied.
Conditions not satisfied.
FAQs on Logical operators
Q1. What is the precedence of logical operators in programming?
Answer:
The precedence of logical operators is: NOT, AND, OR. However, it is always recommended to use
parentheses to make the order of evaluation explicit and avoid confusion.
Q2. Can logical operators be chained together?
Answer:
Yes, logical operators can be chained together to create complex conditions. For example, we can
combine multiple logical AND (&&) or logical OR (||) operators in a single expression to evaluate
multiple conditions simultaneously.
Q3. What will be the output of the following code?
#include <stdio.h>
void main()
{
int a = 1, b = 0, c = 5;
int d = a && b || c++;
printf("%d", c);
}

Answer:
6
Q4. What will be the output of the following code?

#include <stdio.h>
int main()
{
int i = 1;
if (i++ && (i == 1))
printf("GeeksforGeeks\n");
else
printf("Coding\n");
}

Answer:
Coding

Assignment Operators in C/C++


Assignment operators are used to assigning value to a variable. The left side operand of the
assignment operator is a variable and right side operand of the assignment operator is a value. The
value on the right side must be of the same data-type of the variable on the left side otherwise the
compiler will raise an error.
Different types of assignment operators are shown below:
 “=”: This is the simplest assignment operator. This operator is used to assign the value on the
right to the variable on the left.
For example:
 a = 10;
 b = 20;
 ch = 'y';
 “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable
on the left.
Example:
 (a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
 “-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the
current value of the variable on left from the value on the right and then assigns the result to the
variable on the left.
Example:
 (a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
 “*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example:
 (a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
 “/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the variable
on the left.
Example:
 (a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Below example illustrates the various Assignment Operators:

// C program to demonstrate
// working of Assignment operators

#include <stdio.h>

int main()
{

// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("Value of a is %d\n", a);

// Assigning value by adding 10 to a


// using "+=" operator
a += 10;
printf("Value of a is %d\n", a);

// Assigning value by subtracting 10 from a


// using "-=" operator
a -= 10;
printf("Value of a is %d\n", a);

// Assigning value by multiplying 10 to a


// using "*=" operator
a *= 10;
printf("Value of a is %d\n", a);

// Assigning value by dividing 10 from a


// using "/=" operator
a /= 10;
printf("Value of a is %d\n", a);

return 0;
}

Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10

Increment and Decrement Operators in C




The increment ( ++ ) and decrement ( — ) operators in C are unary operators for incrementing
and decrementing the numeric values by 1 respectively. The incrementation and decrementation are
one of the most frequently used operations in programming for looping, array traversal, pointer
arithmetic, and many more.
In this article, we will discuss the increment operator and decrement operator, both their prefix
and postfix applications, and the difference between them.
Increment Operator in C
The increment operator ( ++ ) is used to increment the value of a variable in an expression by 1. It
can be used on variables of the numeric type such as integer, float, character, pointers, etc.
Syntax of Increment Operator
Increment Operator can be used in two ways which are as follows:
// AS PREFIX
++m
// AS POSTFIX
m++

where m is variable.
How to use the increment operator?
Both pre-increment and post-increment increase the value of the variable but there is a little
difference in how they work.
1. Pre-Increment
In pre-increment, the increment operator is used as the prefix. Also known as prefix increment, the
value is incremented first according to the precedence and then the less priority operations are done.
Example
result = ++var1;

The above expression can be expanded as


var = var + 1;
result = var;

2. Post-Increment
In post-increment, the increment operator is used as the suffix of the operand. The increment
operation is performed after all the other operations are done. It is also known as postfix increment.
Example
result = var1++;

The above expression is equivalent


result = var;
var = var + 1;
Example of Increment Operator

// C Program to illustrate the increment of both type


#include <stdio.h>

void increment()
{
int a = 5;
int b = 5;

// PREFIX
int prefix = ++a;
printf("Prefix Increment: %d\n", prefix);

// POSTFIX
int postfix = b++;
printf("Postfix Increment: %d", postfix);
}

// Driver code
int main()
{
increment();

return 0;
}

Output
Prefix Increment: 6
Postfix Increment: 5

As we can see in postfix, the value is incremented after the assignment operator is done.
Note: The post-increment have higher precedence that pre-increment as it is postfix operator while
pre-increment comes in unary operator category.
Decrement Operator in C
The decrement operator is used to decrement the value of a variable in an expression. In the Pre-
Decrement, the value is first decremented and then used inside the expression. Whereas in the Post-
Decrement, the value is first used inside the expression and then decremented.
Syntax
Just like the increment operator, the decrement operator can also be used in two ways:
// AS PREFIX
--m
// AS POSTFIX
m--

where m is variable.
1. Pre-Decrement Operator
The pre-decrement operator decreases the value of the variable immediately when encountered. It is
also known as prefix decrement as the decrement operator is used as the prefix of the operand.
Example
result = --m;

which can be expanded to


m = m - 1;
result = m;

2. Post-Decrement Operator
The post-decrement happens when the decrement operator is used as the suffix of the variable. In
this case, the decrement operation is performed after all the other operators are evaluated.
Example
result = m--;

The above expression can be expanded as


result = m;
m = m-1;

Example of Decrement Operator

// C program to illustrate the decrement operator of both


// types
#include <stdio.h>

void decrement()
{
int a = 5;
int b = 5;

// PREFIX
int prefix = --a;
printf("Prefix = %d\n", prefix);

// POSTFIX
int postfix = b--;
printf("Postfix = %d", postfix);
}

// Driver code
int main()
{
decrement();

return 0;
}

Output
Prefix = 4
Postfix = 5

Differences between Increment and Decrement Operators


The following table list the difference between the increment and decrement operators:
Increment Operator Decrement Operator

Increment Operator adds 1 to the operand. Decrement Operator subtracts 1 from the
Increment Operator Decrement Operator

operand.

The Postfix increment operator means the The Postfix decrement operator means the
expression is evaluated first using the original expression is evaluated first using the original
value of the variable and then the variable is value of the variable and then the variable is
incremented(increased). decremented(decreased).

The Prefix increment operator means the


Prefix decrement operator means the variable
variable is incremented first and then the
is decremented first and then the expression is
expression is evaluated using the new value of
evaluated using the new value of the variable.
the variable.

Generally, we use this in decision-making and This is also used in decision-making and
looping. looping.

Last Updated : 28 Aug, 2023


Conditional or Ternary Operator (?:) in C



The conditional operator in C is kind of similar to the if-else statement as it follows the same
algorithm as of if-else statement but the conditional operator takes less space and helps to write the
if-else statements in the shortest way possible. It is also known as the ternary operator in C as it
operates on three operands.
Syntax of Conditional/Ternary Operator in C
The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
Or the syntax can also be in this form
variable = (condition) ? Expression2 : Expression3;
Or syntax can also be in this form
(condition) ? (variable = Expression2) : (variable = Expression3);
Conditional/Ternary Operator in C

It can be visualized into an if-else statement as:


If (Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary
operators.
Note: The ternary operator have third most lowest precedence, so we need to use the expressions
such that we can avoid errors due to improper operator precedence management.
Working of Conditional/Ternary Operator in C
The working of the conditional operator in C is as follows:
 Step 1: Expression1 is the condition to be evaluated.
 Step 2A: If the condition(Expression1) is True then Expression2 will be executed.
 Step 2B: If the condition(Expression1) is false then Expression3 will be executed.
 Step 3: Results will be returned.
Flowchart of Conditional/Ternary Operator in C
To understand the working better, we can analyze the flowchart of the conditional operator given
below.
Flowchart of conditional/ternary operator in C

Examples of C Ternary Operator


Example 1: C Program to Store the greatest of the two Numbers using the ternary operator
C

// C program to find largest among two

// numbers using ternary operator

#include <stdio.h>

int main()

int m = 5, n = 4;
(m > n) ? printf("m is greater than n that is %d > %d", m, n)

: printf("n is greater than m that is %d > %d", n, m);

return 0;

Output
m is greater than n that is 5 > 4
Example 2: C Program to check whether a year is a leap year using
ternary operator

// C program to check whether a year is leap year or not using ternary operator

#include <stdio.h>

int main()

int yr = 1900;

(yr%4==0) ? (yr%100!=0? printf("The year %d is a leap year",yr)

: (yr%400==0 ? printf("The year %d is a leap year",yr)

: printf("The year %d is not a leap year",yr)))

: printf("The year %d is not a leap year",yr);

return 0;

Output
The year 1900 is not a leap year
FAQs on Conditional/Ternary Operators in C
1. What is the ternary operator in C?

The ternary operator in C is a conditional operator that works on three operands. It works similarly
to the if-else statement and executes the code based on the specified condition. It is also called
conditional Operator

2. What is the advantage of the conditional operator?

It reduces the line of code when the condition and statements are small.

Last Updated : 03 Apr, 2023



Sizeof is a much-used operator in the C. It is a compile-time unary operator which can be used to
compute the size of its operand. The result of sizeof is of the unsigned integral type which is
usually denoted by size_t. sizeof can be applied to any data type, including primitive types such as
integer and floating-point types, pointer types, or compound datatypes such as Structure, union, etc.
Syntax:
sizeof(Expression);
where ‘Expression‘ can be a data type or a variable of any type.
Return: It returns the size size of the given expression.
Time Complexity: O(1)
Auxiliary Space: O(1)
Usage of sizeof() operator
sizeof() operator is used in different ways according to the operand type.
1. When the operand is a Data Type: When sizeof() is used with the data types such as int, float,
char… etc it simply returns the amount of memory allocated to that data types.

Example:

// C Program To demonstrate

// sizeof operator

#include <stdio.h>

int main()

printf("%lu\n", sizeof(char));

printf("%lu\n", sizeof(int));
printf("%lu\n", sizeof(float));

printf("%lu", sizeof(double));

return 0;

Output
1
4
4
8
Note: sizeof() may give different output according to machine, we have
run our program on a 32-bit gcc compiler.
2. When the operand is an expression: When sizeof() is used with
the expression, it returns the size of the expression.
Example:

// C Program To demonstrate

// operand as expression

#include <stdio.h>

int main()

int a = 0;

double d = 10.21;

printf("%lu", sizeof(a + d));

return 0;

Output
8
As we know from the first case size of int and double is 4 and 8 respectively, a is int variable while
d is a double variable. The final result will be double, Hence the output of our program is 8 bytes.
Type of operator
sizeof() is a compile-time operator. compile time refers to the time at which the source code is
converted to a binary code. It doesn’t execute (run) the code inside ().
Example:

// C Program to illustrate

// that the 'sizeof' operator

// is a 'compile time operator'

#include <stdio.h>

int main(void)

int y;

int x = 11;

// value of x doesn't change

y = sizeof(x++);

// prints 4 and 11

printf("%i %i", y, x);

return (0);

Output
4 11
If we try to increment the value of x, it remains the same. This is because x is incremented inside
the parentheses and sizeof() is a compile-time operator.
Need of Sizeof
1. To find out the number of elements in an array: Sizeof can be used to calculate the number of
elements of the array automatically.
Example:
 C

// C Program

// demonstrate the method

// to find the number of elements

// in an array

#include <stdio.h>

int main()

int arr[] = { 1, 2, 3, 4, 7, 98, 0, 12, 35, 99, 14 };

printf("Number of elements:%lu ",

sizeof(arr) / sizeof(arr[0]));

return 0;

Output
Number of elements:11
2. To allocate a block of memory dynamically: sizeof is greatly used in dynamic memory
allocation. For example, if we want to allocate memory that is sufficient to hold 10 integers and we
don’t know the sizeof(int) in that particular machine. We can allocate with the help of sizeof.
Syntax:
int* ptr = (int*)malloc(10 * sizeof(int));



The concept of operator precedence and associativity in C helps in determining which operators
will be given priority when there are multiple operators in the expression. It is very common to have
multiple operators in C language and the compiler first evaluates the operater with higher
precedence. It helps to maintain the ambiguity of the expression and helps us in avoiding
unnecessary use of parenthesis.
In this article, we will discuss operator precedence, operator associativity, and precedence
table according to which the priority of the operators in expression is decided in C language.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the associativity for
each of the operators:

Operator
Precedence Description Associativity

() Parentheses (function call)

[] Array Subscript (Square


1 Left-to-Right
. Dot Operator

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise


2 Right-to-Left
(type) Cast Operator

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift Left-to-Right

< , <= Relational less than, less than or


6 Left-to-Right
> , >= Relational greater than, greater

7 == , != Relational is equal to, is not Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right


Operator
Precedence Description Associativity

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division
14 Right-to-Left
%= , &= Modulus, bitwise AND

^= , |= Bitwise exclusive, inclusive OR

<<=, >>= Bitwise shift left, right

15 , comma (expression separator) Left-to-Right

Operator Precedence in C
Operator precedence determines which operation is performed first in an expression with more
than one operator with different precedence.
Example of Operator Precedence
Let’s try to evaluate the following expression,
10 + 20 * 30
The expression contains two operators, + (plus), and * (multiply). According to the given table,
the * has higher precedence than + so, the first evaluation will be
10 + (20 * 30)
After evaluating the higher precedence operator, the expression is
10 + 600
Now, the + operator will be evaluated.
610

We can verify this using the following C program

// C Program to illustrate operator precedence

#include <stdio.h>
int main()

// printing the value of same expression

printf("10 + 20 * 30 = %d", 10 + 20 * 30);

return 0;

Output
10 + 20 * 30 = 610
As we can see, the expression is evaluated as,10 + (20 * 30) but not as (10 + 20) * 30 due to *
operator having higher precedence.
Operator Associativity
Operator associativity is used when two operators of the same precedence appear in an expression.
Associativity can be either from Left to Right or Right to Left.

Example of Operator Associativity

Let’s evaluate the following expression,


100 / 5 % 2
Both / (division) and % (Modulus) operators have the same precedence, so the order of evaluation
will be decided by associativity.
According to the given table, the associativity of the multiplicative operators is from Left to
Right. So,
(100 / 5) % 2
After evaluation, the expression will be
20 % 2
Now, the % operator will be evaluated.
0
We can verify the above using the following C program:

// C Program to illustrate operator Associativity

#include <stdio.h>

int main()

// Verifying the result of the same expression

printf("100 / 5 % 2 = %d", 100 / 5 % 2);

return 0;

Output
100 / 5 % 2 = 0
Operators Precedence and Associativity are two characteristics of operators that determine the
evaluation order of sub-expressions.
Example of Operator Precedence and Associativity
In general, the concept of precedence and associativity is applied together in expressions. So let’s
consider an expression where we have operators with various precedence and associativity
exp = 100 + 200 / 10 - 3 * 10
Here, we have four operators, in which the / and * operators have the same precedence but have
higher precedence than the + and – operators. So, according to the Left-to-Right associativity
of / and *, / will be evaluated first.
exp = 100 + (200 / 10) - 3 * 10
= 100 + 20 - 3 * 10
After that, * will be evaluated,
exp = 100 + 20 - (3 * 10)
= 100 + 20 - 30
Now, between + and –, + will be evaluated due to Left-to-Right associativity.
exp = (100 + 20) - 30
= 120 - 30
At last, – will be evaluated.
exp = 120 - 30
= 90

Again, we can verify this using the following C program.

// C Program to illustrate the precedence and associativity

// of the operators in an expression

#include <stdio.h>

int main()

// getting the result of the same expression as the

// example

int exp = 100 + 200 / 10 - 3 * 10;

printf("100 + 200 / 10 - 3 * 10 = %d", exp);

return 0;

Output:
100 + 200 / 10 – 3 * 10 = 90

Important Points
There are a few important points and cases that we need to remember for operator associativity and
precedence which are as follows:
1. Associativity is only used when there are two or more operators of the same precedence.
The point to note is associativity doesn’t define the order in which operands of a single operator are
evaluated. For example, consider the following program, associativity of the + operator is left to
right, but it doesn’t mean f1() is always called before f2(). The output of the following program is
in-fact compiler-dependent.
Example

// Associativity is not used in the below program.

// Output is compiler dependent.

#include <stdio.h>

int x = 0;

int f1()

x = 5;

return x;

int f2()

x = 10;

return x;

int main()

int p = f1() + f2();

printf("%d ", x);

return 0;
}

Output
10

2. We can use parenthesis to change the order of evaluation


Parenthesis ( ) got the highest priority among all the C operators. So, if we want to change the
order of evaluation in an expression, we can enclose that particular operator in ( ) parenthesis along
with its operands.
Example
Consider the given expression
100 + 200 / 10 - 3 * 10
= 90
But if we enclose 100 + 200 in parenthesis, then the result will be different.
(100 + 200) / 10 - 3 * 10 = 0
=0
As the + operator will be evaluated before / operator.

3. All operators with the same precedence have the same associativity.
This is necessary, otherwise, there won’t be any way for the compiler to decide the evaluation order
of expressions that have two operators of the same precedence and different associativity. For
example + and – have the same associativity.
4. Precedence and associativity of postfix ++ and prefix ++ are different.
The precedence of postfix ++ is more than prefix ++, their associativity is also different. The
associativity of postfix ++ is left to right and the associativity of prefix ++ is right to left.
See this for examples.

5. Comma has the least precedence among all operators and should be used carefully.
For example, consider the following program, the output is 1.
Example

#include <stdio.h>

int main()

int a;

a = 1, 2, 3; // Evaluated as (a = 1), 2, 3

printf("%d", a);

return 0;
}

Output
1
6. There is no chaining of comparison operators in C
In Python, an expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining
doesn’t happen in C. For example, consider the following program. The output of the following
program is “FALSE”.
Example

#include <stdio.h>

int main()

int a = 10, b = 20, c = 30;

// (c > b > a) is treated as ((c > b) > a), associativity of '>'

// is left to right. Therefore the value becomes ((30 > 20) > 10)

// which becomes (1 > 10)

if (c > b > a)

printf("TRUE");

else

printf("FALSE");

return 0;

Output
FALSE

You might also like