UNIT 1 Introduction
UNIT 1 Introduction
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 :
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.
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.
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.
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.
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.
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:
#include <stdio.h>
int main () {
int a = 10;
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.
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.
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:
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”;
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
Example
int var; // integer variable
char a; // character variable
float fff; // float variables
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
// initialization
defined_var = 12;
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.
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.
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.
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.
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.
----------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.
int main ()
{
// register variable
register int var = 22;
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.
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.
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
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:
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.
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
Example of char
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);
Output
Value of a: a
Value of a after increment is: b
Value of c: c
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
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;
Output
123123123.000000
12.293123
2312312312.123123
Syntax:
// function return type void
void exit (int check);
int print(void);
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
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
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
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).
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);
// 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
Precedenc
e Operator Description Associativity
* Dereference right-to-left
6
Relational greater than/greater than or equal
> , >= left-to-right
to
12 || Logical OR left-to-right
14 = Assignment right-to-left
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
// operators
#include <stdio.h>
int main()
// printing a and b
res = a - b; // subtraction
res = a * b; // multiplication
res = a / b; // division
res = a % b; // modulus
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
Unary Plus
+ Returns the value of its operand. +h
Operator
Increment 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 – –.
// of Unary arithmetic
// operators
#include <stdio.h>
int main()
// post-increment example:
res = a++;
printf("a is %d and result is %d\n", a,
// post-decrement example:
res = a--;
// pre-increment example:
res = ++a;
// pre-decrement example:
// itself
res = --a;
// a and res have same values = 10
return 0;
Output
Post Increment and Decrement
a is 11 and result is 10
a is 10 and result is 11
Example
#include <stdio.h>
int main()
{
int var;
var = 10 * 20 + 15 / 5;
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.
// rectangle
#include <stdio.h>
int main()
int breadth = 5;
// calculating area
// calculating perimeter
// printing results
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.
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++
#include <stdio.h>
int main()
// to negative
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++
#include <stdio.h>
int main()
int a = 5;
int b = 5;
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++
#include <stdio.h>
int main()
int a = 5;
int b = 5;
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++
#include <stdio.h>
int main()
int a = 10;
int b = 5;
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++
// 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++
#include <stdio.h>
int main()
return 0;
}
Output
Size of double: 8
Size of int: 4
Discuss
Courses
Practice
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;
// 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:
int main()
{
int a = 10, b = 4, c = 10, d = 20;
// logical operators
// 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");
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;
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;
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
#include <stdbool.h>
#include <stdio.h>
int main()
int a = 10, b = 4;
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
Discuss
Courses
Practice
Video
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
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>
int res = 0, i;
res ^= arr[i];
return res;
}
// Driver Method
int main(void)
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;
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;
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;
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)
#include <stdio.h>
int main()
unsigned int x = 1;
return 0;
Output
Signed Result -2
Unsigned Result 4294967294
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
// AND Operator
#include <stdio.h>
// Driver code
int main()
else {
return 0;
Output
Both values are greater than 0
2. 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
#include <stdio.h>
// Driver code
int main()
if (a > 0 || b > 0) {
else {
return 0;
Output
Any one of the given value is greater than 0
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
// NOT Operator
#include <stdio.h>
// Driver code
int main()
// it to false
else {
printf("Both values are less than 0\n");
return 0;
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++
#include <iostream>
if (number > 0)
return true;
else
return false;
if (number % 2 == 0)
return true;
else
return false;
// driver code
int main()
int x = 10;
}
else {
int y = -5;
else {
return 0;
Output
Both conditions are satisfied.
Conditions not satisfied.
C++
// C++ program to illustrate the short circuiting in Logical
// OR
#include <iostream>
using namespace std;
// driver code
int main()
{
int x = 8;
int y = -5;
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
// 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);
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
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;
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++;
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;
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--;
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
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).
Generally, we use this in decision-making and This is also used in decision-making and
looping. looping.
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
#include <stdio.h>
int main()
int m = 5, n = 4;
(m > n) ? printf("m is greater than n that is %d > %d", m, n)
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;
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
It reduces the line of code when the condition and statements are small.
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;
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
#include <stdio.h>
int main(void)
int y;
int x = 11;
y = sizeof(x++);
// prints 4 and 11
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
// in an array
#include <stdio.h>
int main()
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
* Dereference Operator
12 || Logical OR Left-to-Right
= Assignment
*= , /= Multiplication, division
14 Right-to-Left
%= , &= Modulus, bitwise AND
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
#include <stdio.h>
int main()
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.
#include <stdio.h>
int main()
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
#include <stdio.h>
int main()
// example
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
#include <stdio.h>
int x = 0;
int f1()
x = 5;
return x;
int f2()
x = 10;
return x;
int main()
return 0;
}
Output
10
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()
// is left to right. Therefore the value becomes ((30 > 20) > 10)
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
Output
FALSE