C_Programming_Theory_Only
C_Programming_Theory_Only
Bridges the gap between low-level programming (closer to hardware and machine
code) and high-level programming (closer to human-readable code).
Referred as the "mother of all programming languages" because it influenced many modern
programming languages like , , and .
C programs are platform-independent i.e. code can be compiled and run on different
systems with minimal modifications.
Does not require heavy runtime environments or libraries, making it ideal for low-resource
systems.
Output
Hello World!
In this C tutorial, we’ll cover everything from basic syntax, data types, and control
structures to advanced topics like pointers, memory management, and file handling. By the
end, you’ll gain hands-on experience and a solid understanding of C, which is essential for
mastering other programming languages like C++ and Java. Let’s dive into the world of C
programming and build a strong coding foundation!
C Overview
C Basics
C Input/Output
C Operators
C Flow Control
C Functions
C Arrays
C Strings
C Pointers
C Dynamic Memory Allocation
C Storage Classes
C Preprocessor
C File Handling
C Error Handling
C Programs
Miscellaneous
C Interview Questions
C Compiler
C compiler is a software that translates human-readable C language code into machine code
or an intermediate code that can be executed by a computer’s central processing unit (CPU).
There are many C compilers available in the market, such as GNU Compiler Collection
(GCC), Microsoft Visual C++ Compiler, Clang, Intel C++ Compiler, and TinyCC (TCC).
For this tutorial, we will be using the GNU-based provided by GeeksforGeeks which is
developed for beginners and is very easy to use compared to other compiler/IDE’s available
on the web.
Features of C Language
There are some key features of C language that show the ability and power of C language:
Simplicity and Efficiency: The simple syntax and structured approach make the C language
easy to learn.
Fast Speed: C is one of the fastest programming language because C is a static programming
language, which is faster than dynamic languages like Javascript and Python. C is also a
compiler-based which is the reason for faster code compilation and execution.
Portable: C provides the feature that you write code once and run it anywhere on any
computer. It shows the machine-independent nature of the C language.
Memory Management: C provides lower level memory management using pointers and
functions like realloc(), free(), etc.
Pointers: C comes with pointers. Through pointers, we can directly access or interact with
the memory. We can initialize a pointer as an array, variables, etc.
Structured Language: C provides the features of structural programming that allows you to
code into different parts using functions which can be stored as libraries for reusability.
Applications of C Language
C was used in programs that were used in making operating systems. C was known as a
system development language because the code written in C runs as fast as the code written
in assembly language.
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
FAQs
The first steps towards learning C or any language are to write a hello world program. It
gives the understanding of how to write and execute a code. After this, learn the following:
Variables
Operators
Conditionals
Functions
Structures
Recursions
While C is one of the easy languages, it is still a good first language choice to start with
because almost all programming languages are implemented in it. It means that once you
learn C language, it’ll be easy to learn more languages like C++, Java, and C#.
Fast Speed
Clean Syntax
These features make the C language suitable for system programming like an operating
system or compiler development.
So, if a person learns C programming first, it will help them to learn any modern
programming language as well. Also, learning C helps to understand a lot of the underlying
architecture of the operating system like pointers, working with memory locations, etc.
C++ was created to add the OOPs concept into the C language so they both have very similar
syntax with a few differences. The following are some of the main differences between C
and C++ Programming languages.
C++ supports OOPs paradigm while C only has the procedural concept of programming.
There are many more differences between C and C++ which are discussed here:
The following code is one of the simplest C programs that will help us understand the basic
syntax structure of a C program.
EXAMPLE
4
5
After the above discussion, we can formally assess the basic structure of a 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 lead to a Compilation Error. The structure of a C
program is as follows:
Components of a C Program:
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 preprocessor which is a program invoked by the compiler. In the above
example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are
called header files in C.
Some of the C Header files:
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 (See for more details). 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. See post for more details on the
return type.
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.
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.
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.
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 like , that can
be used to start development in C without installing a compiler.
Windows: There are many free IDEs available for developing programs in C like and . IDEs
provide us with an environment to develop code, compile it and finally execute it. We
strongly recommend Code Blocks.
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.
macOS: macOS already has a built-in text editor where you can just simply write the code
and save it with a “.c” extension.
Application of C
Operating systems: C is widely used for developing operating systems such as Unix, Linux,
and Windows.
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.
Financial applications: C is used for developing financial applications such as stock market
analysis and trading systems.
The main features of C language include low-level access to memory, a simple set of
keywords, and a clean style, these features make C language suitable for system
programming like an operating system or compiler development.
Procedural Language
Modularity
Statically Type
General-Purpose Language
Middle-Level Language
Portability
Easy to Extend
1. Procedural Language
In a 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.
Newer languages like Java, python offer more features than 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 to solve common
problems.
4. Statically Type
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:
It is a diversified language with a rich set of built-in which are used in writing complex or
simplified C programs.
Robust libraries and help even a beginner coder to code with ease.
8. Middle-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.
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.
Introduction:
The C programming language has several standard versions, with the most commonly used
ones being C89/C90, C99, C11, and C18.
C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in
1989 and 1990, respectively. This standard introduced many of the features that are still
used in modern C programming, including data types, control structures, and the standard
library.
C11 (ISO/IEC 9899:2011) introduced several new features, including _Generic, static_assert,
and the atomic type qualifier. This standard also includes several updates to the library,
including new functions for math, threads, and memory manipulation.
C18 (ISO/IEC 9899:2018) includes updates and clarifications to the language specification
and the library.
C23 standard (ISO/IEC 9899:2023) is the latest revision and include better support for the
const qualifier, new and updated library functions, and further optimizations for compiler
implementations.
When writing C code, it’s important to know which standard version is being used and to
write code that is compatible with that standard. Many compilers support multiple standard
versions, and it’s often possible to specify which version to use with a compiler flag or
directive.
Here are some advantages and disadvantages of using the C programming language:
Advantages:
Efficiency: C is a fast and efficient language that can be used to create high-performance
applications.
Portability: C programs can be compiled and run on a wide range of platforms and
operating systems.
Low-level access: C provides low-level access to system resources, making it ideal for
systems programming and developing operating systems.
Large user community: C has a large and active user community, which means there are
many resources and libraries available for developers.
Widely used: C is a widely used language, and many modern programming languages are
built on top of it.
Disadvantages:
Steep learning curve: C can be difficult to learn, especially for beginners, due to its complex
syntax and low-level access to system resources.
Lack of memory management: C does not provide automatic memory management, which
can lead to memory leaks and other memory-related bugs if not handled properly.
No built-in support for object-oriented programming: C does not provide built-in support
for object-oriented programming, making it more difficult to write object-oriented code
compared to languages like Java or Python.
No built-in support for concurrency: C does not provide built-in support for concurrency,
making it more difficult to write multithreaded applications compared to languages like
Java or Go.
Importance:
Choosing the right programming language: Knowing the advantages and disadvantages of C
can help developers choose the right programming language for their projects. For example,
if high performance is a priority, C may be a good choice, but if ease of use or built-in
memory management is important, another language may be a better fit.
Writing efficient code: Understanding the efficiency advantages of C can help developers
write more efficient and optimized code, which is especially important for systems
programming and other performance-critical applications.
Collaboration and communication: Knowing the advantages and disadvantages of C can also
help developers communicate and collaborate effectively with others on their team or in the
wider programming community.
void main() { }
The above program fails in GCC as the return type of main is void, but it compiles in Turbo
C. How do we decide whether it is a legitimate C program or not?
Consider the following program as another example. It produces different results in
different compilers.
Source:
Which compiler is right?
The answer to all such questions is C standard. In all such cases, we need to see what C
standard says about such programs.
What is C standard?
The latest C standard is , also known as as the final draft was published in 2018. Before C11,
there was . The C11 final draft is available . See for a complete history of C standards.
So the return type void doesn’t follow the standard, and it’s something allowed by certain
compilers.
Let us talk about the second example. Note the following statement in C standard is listed
under unspecified behavior.
C, a language known for its versatility and power, holds a widespread influence across
different programming domains, from system programming to embedded systems. Before
immersing yourself in the intricacies of C programming, it becomes paramount to establish
a robust local development environment on your computer.
C serves as the backbone for numerous applications, owing to its efficiency and close-to-the-
machine capabilities. Whether you are delving into system-level programming or engaging
in the intricacies of embedded systems, the proficiency of C remains unparallеlеd.
To embark on your C programming journey, creating a local development environment
becomes an indispensable initial step. This involves configuring your computer to compile
and run C programs simultaneously. A local environment ensures that you have the
necessary tools and resources at your disposal, facilitating a smooth coding experience.
Integratеd Development Environments (IDEs) play a pivotal role in streamlining the soft
development process. Onlinе IDEs offer a convenient option for those who choose not to set
up a local environment.
Output
Learning C at GeekforGeeks
1. C compiler
Once you've secured and installed a text editor and saved your program with a '. c'
extension, the next step is acquiring a C compiler. This compiler is responsible for
translating your high-level C code into a machine-understandable low-level language. In
other words, we can say that it converts the source code written in a programming language
into another computer language that the computer understands.
Installing GCC on Linux
Wе will install thе GNU GCC compilеr on Linux. To install and work with thе GCC compilеr
on your Linux machinе, procееd according to thе bеlow stеps:
A. First, run the following two commands from your Linux terminal window:
B. Additionally, you can install the build-essential package, which includes essential
libraries for compiling and running C programs:
This command will install all thе librariеs rеquirеd to compilе and run a C program.
C. After completing the above steps, check whether the GCC compiler is installed correctly:
gcc --version
D. If there are no errors in the above steps, your Linux environment is set up to compile C
programs.
E. Writе your program in a tеxt filе and savе it with any filеnamе and '. c' еxtеnsion. Wе
havе writtеn a program to display "Hеllo World" and savеd it in a filе with thе filеnamе
"hеlloworld. c" on thе dеsktop.
F. Open the Linux terminal, navigate to the directory where you saved your file, and compile
it using the following command:
G. After executing the above command, a new file with the name you chose as "any-name"
will be created in the same directory.
./hello
These steps cover the installation of the C compiler, compilation of a C program, and
running the compiled program on a Linux system.
2. Text Editor
Text editors are essential programs used to edit or write text, including C programs. In the
context of C programming, it's crucial to understand that while the typical extension for a
text file is (.txt), files containing C programs should be saved with a '.c' extension. Similarly,
the '.cpp' extension is also acceptable for C++ programs. Files with extensions '.CPP' and '.C'
are termed source code files, housing source code written in the C++ programming
language. These extensions aid the compiler in recognizing that the file contains a C or C++
program.
1. Codе::Blocks Installation
Under the OS X section on the left sidebar, select the "Application" option.
Choose command-line tools from the available options and click the Next button.
In the following window, provide necessary details like organization name, Product Name,
etc.
Select the main.c file from the directory list on the left sidebar.
After opening the main.c file, you'll see a pre-written C program or template.
To run your C program, go to the Product menu and choose the Run option from the
dropdown.
Begin by installing on your Windows system. Opеn thе downloadеd filе and click Run ->
(Accеpt thе agrееmеnt) Nеxt -> Nеxt -> Nеxt -> (chеck all thе options) -> Nеxt -> Install -
> Finish.
Now, you'll be ablе to sее thе Visual Studio Codе icon on your dеsktop.
Aftеr installation, "Continuе. " Chеck all thе Packagеs (Right Click -> Mark for Installation).
Now, click on Installation (lеft cornеr) -> Apply Changеs. (This may takе timе)
Navigatе to This PC -> C Drivе -> MinGW -> Bin. (Copy this path)
Right-click on "This PC" -> Propеrtiеs -> Advancеd Systеm Sеtting -> Environmеnt
variablеs -> (Sеlеct PATH in Systеm variablеs) -> Edit -> Nеw -> Pastе thе path hеrе and
click OK.
Go to Visual Studio Codе and install some usеful еxtеnsions (from thе right sidеbar)
C/C++
Codе Runnеr
Now, go to Sеtting -> Sеttings -> Sеarch for Tеrminal -> Go to thе еnd of this pagе -> Chеck
[ Codе-runnеr: Run In Tеrminal ]
You are good to go now. Opеn any foldеr, crеatе nеw filеs, and savе thеm with thе
еxtеnsion ". c".
Firstly, install Visual Studio Codе for Mac OS using this link - . Thеn, install thе compilеr
MinGW. For this, we first nееd to install Homеbrеw.
To install Homеbrеw, opеn Tеrminal (cmd + spacе). Writе Tеrminal and hit Entеr. In cmd,
copy thе givеn command:
This will download and install HomеBrеw on your Mac system. This process may take time.
Now, install thе MinGW compilеr on Mac OS. Pastе thе givеn command in thе tеrminal and
prеss Entеr.
Go to Visual Studio Codе, and install some usеful еxtеnsions (from thе right sidеbar)
C/C++
Codе Runnеr
Now, go to Sеtting -> Sеttings -> Sеarch for Tеrminal -> Go to thе еnd of this pagе -> Chеck
[ Codе-runnеr: Run In Tеrminal ]
You are good to go now. Opеn any foldеr, crеatе nеw filеs, and savе thеm with thе
еxtеnsion ". c".
By following thеsе comprеhеnsivе stеps, you can еstablish a robust C dеvеlopmеnt
еnvironmеnt, whеthеr you choosе a local sеtup or an onlinе IDE.
The “Hello World” program is the first step towards learning any programming language. It
is also one of the simplest programs that is used to introduce aspiring programmers to the
programming language. It typically outputs the text “Hello, World!” to the console screen.
To print the “Hello World”, we can use the from the stdio.h library that prints the given
string on the screen. Provide the string “Hello World” to this function as shown in the below
code:
10
11
Output
Hello World
Explanation:
To go beyond the basics and explore data structures and more advanced topics, the takes
you from beginner to expert
The compilation is the process of converting the source code of the C language into machine
code. As C is a mid-level language, it needs a compiler to convert it into an executable code
so that the program can be run on our machine.
Compilation Process in C
We first need a compiler and a code editor to compile and run a C Program. The below
example is of an Ubuntu machine with GCC compiler.
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
We use the following command in the terminal for compiling our filename.c source file
$ gcc filename.c –o filename
We can pass many instructions to the GCC compiler to different tasks such as:
The option -Wall enables all compiler’s warning messages. This option is recommended to
generate better code.
The option -o is used to specify the output file name. If we do not use this option, then an
output file with the name a.out is generated.
If there are no errors in our C program, the executable file of the C program will be
generated.
After compilation executable is generated and we run the generated executable using the
below command.
$ ./filename
The program will be executed and the output will be shown in the terminal.
A compiler converts a C program into an executable. There are four phases for a C program
to become an executable:
Pre-processing
Compilation
Assembly
Linking
By executing the below command, we get all intermediate files in the current directory
along with the executable.
Intermediate Files
This is the first phase through which source code is passed. This phase includes:
Removal of Comments
Expansion of Macros
Conditional compilation
The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i:
using $vi filename.i
In the above output, the source file is filled with lots and lots of info, but in the end, our code
is preserved.
2. Compiling
The next step is to compile filename.i and produce an; intermediate compiled output
file filename.s. This file is in assembly-level instructions. Let’s see through this file
using $nano filename.s terminal command.
The snapshot shows that it is in assembly language, which the assembler can understand.
3. Assembling
In this phase the filename.s is taken as input and turned into filename.o by the assembler.
This file contains machine-level instructions. At this phase, only existing code is converted
into machine language, and the function calls like printf() are not resolved. Let’s view this
file using $vi filename.o
Binary Code
4. Linking
This is the final phase in which all the linking of function calls with their definitions is done.
Linker knows where all these functions are implemented. Linker does some extra work also,
it adds some extra code to our program which is required when the program starts and
ends. For example, there is a code that is required for setting up the environment like
passing command line arguments. This task can be easily verified by using $size
filename.o and $size filename. Through these commands, we know how the output file
increases from an object file to an executable file. This is because of the extra code that
Linker adds to our program.
Note: GCC by default does dynamic linking, so printf() is dynamically linked in above
program. Refer , and for more details on static and dynamic linking.
Tokens in C
In C programming, tokens are the smallest units in a program that have meaningful
representations. Tokens are the building blocks of a C program, and they are recognized by
the C compiler to form valid expressions and statements. Tokens can be classified into
various categories, each with specific roles in the program.
Types of Tokens in C
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:
Table of Content
1. Punctuators
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(): These special symbols are 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 (, ): It is used to separate more than one statement like for separating parameters in
function calls.
Asterisk (*): It is used to create a pointer variable and for the multiplication of variables.
Assignment operator(=): It is used to assign values and for logical operation validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
Example:
8
Output
Hello, World!
2. Keywords
are reserved words that have predefined meanings in C. These cannot be used as identifiers
(variable names, function names, etc.). Keywords define the structure and behavior of the
program C language supports 32 keywords some of them are:
Example:
10
11
12
Output
5
Note: The number of keywords may change depending on the version of C you are using.
For example, keywords present in ANSI C are 32 while in C11, it was increased to 44.
Moreover, in the latest c23, it is increased to around 54.
3. 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:
Output
Hello, World!
4. 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 the number of operands that an operator can act upon, operators can be
classified as follows:
Unary Operators: Those operators that require only a single operand to act upon are known
as unary operators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
Arithmetic operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called the
ternary operator. Conditional Operator(?) is also called the ternary operator.
Example:
10
Output
15
5. Identifiers
are names given to variables, functions, arrays, and other user-defined items. They must
begin with a letter (a-z, A-Z) or an underscore (_) and can be followed by letters, digits (0-9),
and underscores.
Example:
Output
10
6. Constants
are fixed values used in a C program. These values do not change during the execution of
the program. Constants can be integers, floating-point numbers, characters, or strings.
Examples:
4
5
Output
100
C Identifiers
In C programming, identifiers are the names used to identify variables, functions, arrays,
structures, or any other user-defined items. It is a name that uniquely identifies a program
element and can be used to refer to it later in the program.
Example:
void func() {}
Underscore (_).
The first character of an identifier must be a letter or an underscore.
The below image and table show some valid and invalid identifiers in C language.
Examples of Identifiers
10
11
var = 10;
12
13
14
15
16
17
Output
10
If you are not familiar with the concept discussed here, don’t worry! We will discuss them in
the later sections.
10
11
12
13
14
Output
30
Explanation: In this code, identifier sum is the name of the user-defined function that takes
two parameters (a and b) as its identifiers. The main function is the program’s entry point,
and printf is a standard library function.
Keywords vs Identifiers
Here’s a table that highlights the differences between Keywords and Identifiers in C:
In the below code, we have used const as an identifier which is a keyword in C. This will
result in an error in the output.
Output
./Solution.c: In function 'main':
Keywords in C
In C Programming language, there are many rules so to avoid different types of errors. One
of such rule is not able to declare variable names with auto, long, etc. This is all because
these are keywords. Let us check all keywords in C language.
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program. A list of
keywords in C or reserved words in the C programming language are mentioned below:
auto
auto is the default storage class variable that is declared inside a function or a block. auto
variables can only be accessed within the function/block they are declared. By default, auto
variables have garbage values assigned to them. Automatic variables are also called local
variables as they are local to a function.
Here num is the variable of the storage class auto and its type is int. Below is the C program
to demonstrate the auto keyword:
4
5
10
11
12
13
14
printvalue();
15
16
Output
10
The break statement is used to terminate the innermost loop. It generally terminates a loop
or a break statement. The continue statement skips to the next iteration of the loop. Below
is the C program to demonstrate break and continue in C:
4
5
10
if (i == 2)
11
12
13
14
if (i == 6)
15
16
17
18
19
20
21
Output
1345
The switch statement in C is used as an alternate to the if-else ladder statement. For a single
variable i.e, switch variable it allows us to execute multiple operations for different possible
values of a single variable.
switch(Expression)
{
case '1': // operation 1
break;
case:'2': // operation 2
break;
default: // default statement to be executed
}
10
11
12
13
14
15
16
17
default:
18
19
20
Output
Case 4
Note: it is best to add a break statement after every case so that switch statement doesn’t
continue checking the remaining cases.
Output
Case 4
Default
char
char x = 'D';
char c = 'a';
9
10
Output
const
a = a + 2;
10
11
This code will produce an error because the integer a was defined as a constant and it’s
value was later on changed.
Output:
The do statement is used to declare a do-while loop. A do-while loop is a loop that executes
once, and then checks it’s condition to see if it should continue through the loop. After the
first iteration, it will continue to execute the code while the condition is true.
10
11
i++;
12
13
14
15
Output
12345
double and float
The doubles and floats are datatypes used to declare decimal type variables. They are
similar, but doubles have 15 decimal digits, and floats only have 7.
Example:
float f = 0.3;
double d = 10.67;
10
11
12
Output
The if-else statement is used to make decisions, where if a condition is true, then it will
execute a block of code; if it isn’t true (else), then it will execute a different block of code.
if(marks == 97) {
// if marks are 97 then will execute this block of code
}
else {
// else it will execute this block of code
}
10
11
12
13
else
14
15
16
17
18
19
Output
A is less than 11
enum
The keyword is used to declare an enum (short for enumeration). An enum is a user-
defined datatype, which holds a list of user-defined integer constants. By default, the value
of each constant is it’s index (starting at zero), though this can be changed. You can declare
an object of an enum and can set it’s value to one of the constants you declared before. Here
is an example of how an enum might be used:
10
11
12
13
14
day = Wed;
15
16
17
Output
extern
The keyword is used to declare a variable or a function that has an external linkage outside
of the file declaration.
extern int a;
8
9
10
for
The “for” keyword is used to declare a for-loop. A for-loop is a loop that is specified to run a
certain amount of times.
10
11
12
13
Output
01234
goto
The goto statement is used to transfer the control of the program to the given label. It is
used to jump from anywhere to anywhere within a function.
Example:
void printNumbers() {
10
label:
11
12
n++;
13
14
15
16
17
18
printNumbers();
19
20
Output
1 2 3 4 5 6 7 8 9 10
int
Example:
void sum() {
sum = a + b;
10
11
12
13
14
sum();
15
16
Output
30
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.
Below is the C program to demonstrate the short, long, signed, and unsigned keywords:
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Output
The return statement returns a value to where the function was called.
Example:
sum = x + y;
10
11
12
13
14
15
sum(num1, num2));
16
17
Output
Sum: 30
sizeof
sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in
bytes.
Example:
sizeof(char);
sizeof(int);
sizeof(float); in bytes.
10
Output
register
Register variables tell the compiler to store variables in the CPU register instead of memory.
Frequently used variables are kept in the CPU registers for faster access.
Example:
static
The static keyword is used to create static variables. A static variable is not limited by a
scope and can be used throughout the program. It’s value is preserved even after it’s scope.
For Example:
struct
For Example:
char title[50];
char author[50];
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Output
typedef
The typedef keyword in C programming language is used to define a data type with a new
name in the program. typedef keyword is used to make our code more readable.
For Example:
In this example we have changed the datatype name of “long” to “num”.
union
The union is a user-defined data type. All data members which are declared under the union
keyword share the same memory location.
Example:
char marks;
s.age = 15;
10
s.marks = 56;
11
12
13
Output
age = 56
marks = 56
void
The void keyword means nothing i.e, NULL value. When the function return type is used as
the void, the keyword void specifies that it has no return value.
Example:
void fun() {
// program
}
volatile
The keyword is used to create volatile objects. Objects which are declared volatile are
omitted from optimization as their values can be changed by code outside the scope of the
current code at any point in time.
For Example:
marks are declared constant so they can’t be changed by the program. But hardware can
change it as they are volatile objects.
while
The keyword is used to declare a while loop that runs till the given condition is true.
Example:
7
8
i++;
10
11
12
13
Output
Hi
Hi
Hi
Conclusion
In this article, the points we learned about the keywords are mentioned below:
Keywords in C – FAQs
Keywords in C are reserved words that have certain meanings and cannot be declare as any
element’s name. For example: for is used for declaring loop and it can’t be declared as an
element’s name.
Sizeof is a keyword that gets the size of an expression, (variables, arrays, pointers, etc.) in
bytes.
What is the default keyword in C?
The default keyword in C is used to specify the default case for the switch statement.
Keywords are reserved words that have some meaning whereas identifiers are the name-
generated names for any variable, struct, class, object, or function in C.
C Comments
Example:
Output
Hello
Table of Content
Single-line Comments
Single-line comments are used to comment out a single line of code or a part of it. These
comments start with two forward slashes (//), and everything after the slashes on that line
is considered a comment. They are also called C++ Style comments as they were first
introduced in C++ and later adopted in C also.
Syntax:
Example:
10
11
Output
Value of x: 5
In this example, the comments provide explanations about the code. The compiler ignores
the comments and does not execute them.
We can also create a comment that displays at the end of a line of code using a single-line
comment. But generally, it’s better to practice putting the comment before the line of code.
Output
Welcome to GeeksforGeeks
Multi-line Comments
Multi-line comments are used for longer descriptions or for commenting out multiple lines
of code. These comments begin with /* and end with */. Everything between these markers
is treated as a comment.
Syntax:
Example:
1
2
*/
10
11
12
Output
Welcome to GeeksforGeeks
Nesting Comments
In C, comments cannot be nested. That means you cannot place a multi-line comment inside
another multi-line comment. If you try to do so, the compiler will treat the closing */ of the
inner comment as the end of the entire multi-line comment.
2
3
*/
10
11
Output
If nested comments are needed, it’s best to use single-line comments or comment out
individual parts.
4
5
10
11
Output
Do not comment on every line unnecessarily and avoid writing obvious comments.
Focus on explaining the intent behind the code rather than restating the obvious.
C Variables
Example:
a = 25;
10
11
12
Output
25
Explanation: In the given program, a is a variable that serves as a name for a memory
location to store an integer value. It store the value 25 and later retrieve it
for printing without needing to reference its full memory address.
Syntax
In C, we have to declare the type of data the variable would store along with the name while
creating a variable:
data_type variable_name;
This data_type decides how much memory a variable need. We can choose the provided by
C language to store different type of data in the variable.
We can also create multiple variables in a single statement by separating them using
comma:
Example
The above syntax is called variable definition. In this, a variable is only named and allocated
some memory to it. No data is stored in it till now.
The data is first entered in the variable in the process called variable initialization. It is
nothing but assigning some initial value to it using assignment operator (=).
variable_name = value;
Example of Variable
5
6
10
age = 18;
11
12
13
14
15
16
17
math = 'A';
18
physics = 'A';
19
chemistry = 'B';
20
arts = 'C';
21
sports = 'C';
22
23
24
25
26
27
28
29
30
Output
Age: 25
---Grades----
Mathematics: A
Physics: A
Chemistry: B
Arts: C
Sports: C
We can assign any name to the variable as long as it follows the following rules:
A variable name must start with an alphabet or an underscore only. It cannot start with a
digit.
C Variables – FAQs
No, variable names in C must begin with a letter or an underscore. Starting with a number is
not allowed.
No, you cannot store different type of data in a variable of different type.
No, once a variable is declared with a type in C, its type cannot be changed.
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they
are declared in the C program. The type of constant can be an integer constant, a floating
pointer constant, a string constant, or a character constant. In C language,
the const keyword is used to define the constants.
In this article, we will discuss about the constants in C programming, ways to define
constants in C, types of constants in C, their properties and the difference between literals
and constants.
What is a constant in C?
Example of Constants in C
10
11
12
13
14
15
16
17
int_const);
18
19
char_const);
20
21
float_const);
22
23
24
Output
One thing to note here is that we have to initialize the constant variables at declaration.
Otherwise, the variable will store some garbage value and we won’t be able to change it. The
following image describes examples of incorrect and correct variable definitions.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list of
the types of constants
Integer Constant
Character Constant
Array Constant
Structure Constant
We just have to add the const keyword at the start of the variable declaration.
Properties of Constant in C
The important properties of constant variables in C defined using the const keyword are as
follows:
We can only initialize the constant variable in C at the time of its declaration. Otherwise, it
will store the garbage value.
2. Immutability
The constant variables in c are immutable after its definition, i.e., they can be initialized only
once in the whole program. After that, we cannot modify the value stored inside that
variable.
7
8
10
var = 20;
11
12
13
14
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
The constant and literals are often confused as the same. But in C language, they are
different entities and have different semantics. The following table lists the differences
between the constants and literals in C:
We can also define a constant in C using . The constants defined using #define are macros
that behave like a constant. These constants are not handled by the compiler, they are
handled by the preprocessor and are replaced by their value before compilation.
3
4
10
Output
Note: This method for defining constant is not preferred as it may introduce bugs and make
the code difficult to maintain.
FAQs on C Constants
Answer:
Constants in C are the immutable variables whose values cannot be modified once they are
declared in the C program.
Answer:
The const keyword is the qualifier that is used to declare the constant variable in C
language.
Answer:
Answer:
The right way to declare a constant in C is to always initialize the constant variable when we
declare.
Q5. What is the difference between constant defined using const qualifier and #define?
Answer:
The following table list the differences between the constants defined using const qualifier
and #define in C:
Answer:
Yes, we can take advantage of the loophole created by pointers to change the value of a
variable declared as a constant in C. The below C program demonstrates how to do it.
10
11
12
int* ptr
13
14
15
*ptr = 500;
16
17
18
19
20
Output
Related Article –
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.
Table of Content
The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values, and
decimal values can be stored in int data type in C.
Size: 4 bytes
Format Specifier: %d
Syntax of Integer
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.
short int: It is lesser in size than the int by 2 bytes so can only store values from -32,768 to
32,767.
long int: Larger version of the int datatype so can store values greater than int.
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 to check the actual
size of any data type.
Example of int
1
10
11
12
13
14
15
16
17
18
19
20
21
c);
22
23
24
25
Output
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.
Size: 1 byte
Format Specifier: %c
Syntax of char
char var_name;
Example of char
2
3
char a = 'a';
char c;
10
11
a++;
12
13
14
15
16
17
18
19
c = 99;
20
21
22
23
24
Output
Value of a: a
Value of c: c
Size: 4 bytes
Format Specifier: %f
Syntax of float
float var_name;
Example of Float
4
5
float a = 9.0f;
float b = 2.5f;
10
11
float c = 2E-4f;
12
13
14
15
16
17
Output
9.000000
2.500000
0.000200
A 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.
Size: 8 bytes
Syntax of Double
The variable can be declared as double precision floating point using the double keyword:
double var_name;
Example of Double
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
10
11
12
13
14
15
16
17
18
Output
123123123.000000
12.293123
2312312312.123123
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 .
Syntax:
Example of Void
4
5
10
11
Output
30
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
8
9
10
11
12
13
14
size_of_char);
15
16
size_of_float);
17
18
size_of_double);
19
20
21
Output
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.
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.
In C, data type modifiers are the keywords used to modify the original sign or length/range
of values that various primitive data types hold such as int, char, and double.
10
Output
ui: 4294967196
Explanation: An unsigned int cannot represent negative values, so when -100 is assigned
to ui, it wraps around to the maximum value of unsigned int plus 1 and subtracts 100,
resulting in 4294967196. The %u format specifier ensures the value is printed as an
unsigned integer.
Table of Content
short Modifier
The short modifier in C works with integer data type. It decreases the size of the int to 2
bytes along with the range of values int type can store.
Example
short int b;
9
10
11
Output
Size of int: 4
Explanation: We initialized a normal integer ‘a’ and short integer ‘b’. After that, we have
printed the size of both the variables and we can clearly see in the output that variable
declared with data modifier with ‘short’ became 2 bytes
Note: The sizes of data type considered in this article are according to 32-bit compiler.
long Modifier
The is used to increase the original size of an int or double data type by two times. As the
consequence, the range of values these data types can store is also increased. For example, if
int take 4 bytes of space it will take 8 bytes of space after using long with int.
Example
8
9
double dub_num;
10
11
12
13
14
15
sizeof(long_long_num));
16
17
18
sizeof(long_dub_num));
19
20
21
Output
num: 4
long_num: 8
long_long_num: 8
dub_num: 8
long_dub_num: 16
Explanation: We have declared the variables of integer and double type with and without
using long modifier and then printed the size of each variable. In the output, we can see that
the size of data type with long modifier becomes double.
unsigned Modifier
By default, we can store positive and negative values in integer data type but many times,
we don’t need to store the negatives values leading to the waste of memory space. We can
utilize this space to store positive values using unsigned data type modifier.
The unsigned modifier shifts the data type range to the positive part of the whole numbers.
For example, if the default range of int is -2,147,483,648 to 2,147,483,647, then after using
unsigned with int, the range became 0 to 4,294,967,295.
Unsigned modifier can also be combined with long and short modifiers to create unsigned
long, unsigned short, etc.
Example
10
11
12
13
Output
signed Modifier
It is default modifier of int and char data type if no modifier is specified. It indicates that we
can store both negative and positive values and the range is equally divided to the positive
and negative values.
Example
10
11
Output
The below table lists the size and the range of data type (in 64-bit compiler) that is changed
with the help of modifiers:
Type Conversion in C
In C, type conversion refers to the process of converting one data type to another. It can be
done automatically by the compiler or manually by the programmer. The type conversion is
only performed to those data types where conversion is possible.
float f1 = 5.5;
a = f1;
9
10
11
float f2 = (float)a;
12
13
14
15
16
17
Output
a: 5
f1: 5.500000
f2: 5.000000
Explanation: In the above program, when f1 is assigned to int a, its value is automatically
converted to integer first and then assigned to a. On the other hand, we manually convert
the value of a to assign it to float variable f2.
The automatic type conversion performed by the compiler is called Implicit Type
Conversion and the manual one done by the programmer is called Explicit Type Conversion.
Implicit type conversion, also known as type coercion, occurs when the C compiler
automatically converts one data type to another without the need for explicit instructions
from the programmer. This typically happens when a smaller data type is assigned to a
larger data type or when different data types are involved in an arithmetic operation.
For example, if an integer is added to a float, the integer is implicitly converted to a float,
and the result is a float.
Example
float n2 = 4.5;
10
11
12
Output
9.50
Explanation: In this code, implicit type conversion occurs when n1 (int) is automatically
converted to a float during the expression n1 + n2 to match the type of n2.
Note: It is possible for type conversions to lose information. Signs can be lost when signed is
implicitly converted to unsigned, and overflow can occur when long is converted to float.
Conversion Rank:
Refers to the priority assigned to data types during conversions, where types with higher
rank (e.g., double) are converted to lower rank types (e.g., int) only when necessary.
Promotion:
Involves converting a smaller data type to a larger one (e.g., int to float).
Demotion:
Converts a larger data type to a smaller one (e.g., float to int), often leading to loss of
precision or data truncation.
Explicit type conversion, or , occurs when the programmer explicitly tells the compiler to
convert a variable from one type to another. This is done using the casting operator (type).
Syntax
where type indicates the final data type to which the expression is converted.
Example
float n1 = 7.9;
6
7
n2 = (int)n1;
10
11
12
13
Output
Explanation: In this example, the float n1 is manually cast to an integer using (int)n1. This
conversion truncates the decimal part, resulting in the integer value being assigned to n2.
Assigning a double to an int without explicit casting will cause a loss of data. The fractional
part of the double will be discarded, and only the integer part will be stored.
Converting a float to a char can be dangerous and may result in data truncation. When a
float is cast to a char, it is converted to its integer value, and only the least significant byte of
that integer is stored in the char (which is 1 byte).
Can I mix int and unsigned int in the same expression safely in C?
Mixing int and unsigned int in the same expression can lead to unexpected results due to
implicit type conversion. When an int is combined with an unsigned int, the int is
automatically promoted to unsigned int. If the int holds a negative value, the result can be a
very large positive number, causing logical errors
Operators in C
Last Updated : 11 Oct, 2024
What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables. The values and variables used with operators are called operands. So we can say
that the operators are the symbols that perform operations on operands.
For example,
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. To dive deeper
into how operators are used with data structures, the covers this topic thoroughly.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on
their functionality:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Other Operators
1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on
operands. There are 9 arithmetic operators in C language:
10
11
12
13
14
15
16
17
18
19
20
21
Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26
2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.
6
7
10
11
12
13
14
15
16
17
18
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
3. Logical Operator in C
10
11
12
13
14
15
Output
a && b : 1
a || b : 1
!a: 0
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.
10
11
12
13
14
15
16
17
18
Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
a >> b: 0
a << b: 800
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.
The assignment operators can be combined with some other operators in C to provide
multiple operations using single operator. These operators are called compound operators.
7
8
10
11
12
13
14
15
16
17
18
19
20
21
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a >>= b: 0
a <<= b: 0
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:
sizeof Operator
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)
Comma Operator ( , )
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
Syntax
operand1 , operand2
Conditional Operator ( ? : )
Syntax
Member operators are used to reference individual members of classes, structures, and
unions.
Syntax
structure_variable . member;
and
To know more about dot operators refer to article and to know more about arrow(->)
operators refer to article.
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 ].
Syntax
The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
10
11
12
13
14
15
16
17
Output
sizeof(num) = 4 bytes
&num = 0x7ffe2b7bdf8c
*add_of_num = 10
Operators can also be classified into three types on the basis of the number of operands
they work on:
Operator Precedence and Associativity is the concept that decides which operator will be
evaluated first in the case when there are multiple operators present in an expression.
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.
To know more about operator precedence and associativity, refer to this article –
Conclusion
In this article, the points we learned about the operator are as follows:
There are six types of operators, Arithmetic Operators, Relational Operators, Logical
Operators, Bitwise Operators, Assignment Operators, and Miscellaneous Operators.
Operators can also be of type unary, binary, and ternary according to the number of
operators they are using.
Every operator returns a numerical value except logical, relational, and conditional operator
which returns a boolean value (true or false).
There is a Precedence in the operators means the priority of using one operator is greater
than another operator.
FAQs on C Operators
Answer:
Answer:
Unary operator
Arithmetic operator
Relational operator
Logical operator
Bitwise operator
Assignment operator
Conditional operator
Q3. What is the difference between the ‘=’ and ‘==’ operators?
Answer:
‘=’ 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.
Answer:
In prefix operations, the value of a variable is incremented/decremented first and then the
new value is used in the operation, whereas, in postfix operations first the value of the
variable is used in the operation and then the value is incremented/decremented.
Example:
b=c=10;
a=b++; // a==10
a=++c; // a==11
Answer:
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
In C programming, input and output operations refer to reading data from external sources
and writing data to external destinations outside the program. C provides a standard set of
functions to handle input from the user and output to the screen or to files. These functions
are part of the standard input/output library <stdio.h>.
In C, there are many functions used for input and output in different situations but the most
commonly used functions for Input/Output are scanf() and printf() respectively.
The function is used to print formatted output to the standard output stdout (which is
generally the console screen). It is one of the most commonly used functions in C.
Syntax
Example:
2
3
Output
First Print
Explanation: The printf() function sends the string “First Print” to the output stream,
displaying it on the screen.
8
9
10
Output
Age: 22
Here, the value of variable age is printed. You may have noticed %d in the formatted string.
It is actually called which are used as placeholders for the value in the formatted string.
You may have also noticed ‘\n’ character. This character is an and is used to enter a newline.
is used to read user input from the console. It takes the format string and the addresses of
the variables where the input will be stored.
Syntax
Remember that this function takes the address of the arguments where the read value is to
be stored.
Example
9
10
11
12
13
Output:
Age is: 25
Explanation: %d is used to read an integer; and &age provides the address of the variable
where the input will be stored.
Example:
6
7
Output
Hi!
Explanation: In this program, the printf function is used to output the text “Hi!” to the
console.
Table of Content
Syntax of printf
Parameter:
formatted_string: It is a string that specifies the data to be printed. It may also contain a
format specifier as a placeholder to print the value of any variable or value.
Return Value:
Returns the number of characters printed after successful execution.
To learn how to make the most of printf() and other input/output functions in C, explore
our, which covers essential I/O operations in detail.
The format string inside printf() can include various format specifiers whose primary
function is to act as a placeholder for printing the variables and values. These format
specifiers start with the percentage symbol (%).
In addition to working as placeholders, format specifiers can also contain a few more
instructions to manipulate how the data is displayed in the output.
%[flags][width][.precision][length]specifier
1. Specifier
It is the character that denotes the type of data. Some commonly used specifiers are:
2. Width
It is the sub-specifier that denotes the minimum number of characters that will be printed.
If the number of characters is less than the specified width, the white space will be used to
fill the remaining characters’ places.
But if the number of characters is greater than the specified width, all the characters will be
still printed without cutting off any.
3. Precision
Precision sub specifier meaning differs for different data types it is being used with.
For Integral data(d, i, u, o, x, X): Specifies the minimum number of digits to be printed. But
unlike the width sub-specifier, instead of white spaces, this sub-specifier adds leading
zeroes to the number. If the number has more digits than the precision, the number is
printed as it is.
For Float or Double Data(f, e, a, A): Specifies the number of digits to be printed after the
decimal point.
4. Length
Specifies the length of the data type in the memory. It is used in correspondence with
Examples of printf() in C
The below examples demonstrate the use of printf() in our C program for different
purposes.
Print a Variable
a + b);
9
10
Output
Explanation: In this program, the format specifier %d is used to print integers variables
using printf. Here, it prints the values of a, b, and the result of a + b.
Print a Literal
99 + 1);
Output
Explanation: The format specifier %d is used to print integer literals. It substitutes 99, 1,
and the result of 99 + 1 into the string.
We can right align the output using the width specifier with positive value.
2
3
Output
Welcome to GfG!
Explanation: The format specifier %100s prints the string s right-aligned with a minimum
width of 100 characters. If the string is shorter than 100 characters, it is padded with spaces
on the left.
If we pass negative width, the minimum width will be the absolute value of the width, but
the text will be left aligned.
5
6
10
Output
Explanation: The format specifier %-50s prints the string s left-aligned with a minimum
width of 50 characters. The remaining spaces are padded with blanks, followed by
printing Geeks.
Output
Explanation: The format specifier %.10d ensures the integer n is printed with a precision
of 10 digits. If n has fewer digits, it is left-padded with zeros to meet the required precision.
For floating point values, precision limits the number of digits to be printed after decimal
points.
float f = 2.451;
Output
2.45
Explanation: The format specifier %.2f ensures the floating-point number f is printed
with 2 digits after the decimal point. It rounds the value if necessary.
Output
Welcome
In C programming language, scanf is a function that stands for Scan Formatted String. It is
used to read data from stdin (standard input stream i.e. usually keyboard) and then writes
the result into the given arguments.
It accepts character, string, and numeric data from the user using standard input.
Here,
If you’re interested in learning more about input handling and integrating it into complex
data structures, the covers practical applications of input functions in C.
Example:
The scanf will write the value input by the user into the integer variable var.
<0: Read error encountered or end-of-file(EOF) reached before any assignment was made.
Why &?
While scanning the input, scanf needs to store that input data somewhere. To store this
input data, scanf needs to known the memory location of a variable. And here comes the
ampersand to rescue.
Example of scanf
10
11
12
13
14
15
16
17
a , b);
18
19
20
Output
Related Article:
. Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or
scanned in input and output operations. They always start with a % symbol and are used in
the formatted string in functions like printf(), scanf, sprintf(), etc.
The C language provides a number of format specifiers that are associated with the different
data types such as %d for int, %c for char, etc. In this article, we will discuss some
commonly used format specifiers and how to use them.
The below table contains the most commonly used format specifiers in C
The %c is the format specifier for the char data type in C language. It can be used for both
formatted input and formatted output in C language.
Syntax:
Example:
char c;
Input:
Output:
We can use the signed integer format specifier %d in the scanf() and print() functions or
other functions that use formatted string for input and output of int data type.
Syntax:
Example:
Input:
Output:
The %u is the format specifier for the unsigned integer data type. If we specify a negative
integer value to the %u, it converts the integer to its 2’s complement.
Syntax:
Enter an integer: 25
Output:
The %f is the floating point format specifier in C language that can be used inside the
formatted string for input and output of float data type. Apart from %f, we can
use %e or %E format specifiers to print the floating point value in the exponential form.
Syntax:
Example:
float a = 12.67;
10
11
12
Output
We can use the %o format specifier in the C program to print or take input for the unsigned
octal integer number.
Syntax:
Example:
Output
103
The %x format specifier is used in the formatted string for hexadecimal integers. In this
case, the alphabets in the hexadecimal numbers will be in lowercase. For uppercase
alphabet digits, we use %X instead.
Syntax:
Example:
1
Output
3c5e
3C5E
Syntax:
Example:
7
8
Output
Hi Geeks
Example: The working of %s with scanf() is a little bit different from its working with
printf(). Let’s understand this with the help of the following C program.
char str[50];
Input
Output
Hi
As we can see, the string is only scanned till a whitespace is encountered. We can avoid that
by using .
The C language also provides the format specifier to print the address/pointers. We can use
%p to print addresses and pointers in C
Syntax
Example:
3
4
Output
C language provides some tools using which we can format the input and output. They are
generally inserted between the % sign and the format specifier symbol Some of them are as
follows:
A number after % specifies the minimum field width to be printed if the characters are less
than the size of the width the remaining space is filled with space and if it is greater then it
is printed as it is without truncation.
Precision tells the minimum number of digits in an integer, the maximum number of
characters in a string, and the number of digits after the decimal part in a floating value.
8
9
10
11
Output
geeksforgeeks
geeksforgeeks
geeks
geeks
No, the C language does not provide a format specifier for binary numbers.
The input and output functions in C take a string as an argument that decides how the data
is displayed on the screen or the data is retrieved to the memory. This string is called the
formatted string.
Escape Sequence in C
The escape sequence in C is the characters or the sequence of characters that can be used
inside the string literal. The purpose of the escape sequence is to represent the characters
that cannot be used normally using the keyboard. Some escape sequence characters are the
part of ASCII charset but some are not.
Different escape sequences represent different characters but the output is dependent on
the compiler you are using.
The following are the escape sequence examples that demonstrate how to use different
escape sequences in C language.
"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");
10
Output
3
4
10
11
12
Output
Hi Geeks
Output
Hello
GeeksforGeeks
10
11
12
Output
Hello GFG
4
5
10
11
12
13
Output
Hello friends
Welcome to GFG
9
10
Output
GeeksforGeeks
10
11
12
Output
Hello\GFG
Explanation: It contains two ‘\’ which means we want print ‘\’ as output.
2
3
10
Output
10
11
12
13
Output
??!
char* s = "A\072\065";
10
11
12
Output
A:5
Explanation: Here 000 is one to three octal digits(0….7) means there must be at least one
octal digit after \ and a maximum of three. Here 072 is the octal notation, first, it is
converted to decimal notation which is the ASCII value of char ‘:’. At the place of \072, there
is: and the output is A:5.
C Preprocessors
C File Handling
C Programs
C Cheatsheet
C Interview Questions
C MCQ
C++
10
11
12
13
C Basics
15
16
C Data Types
17
Data Types in C
18
Literals in C
19
Escape Sequence in C
20
bool in C
21
Integer Promotions in C
22
Character Arithmetic in C
23
Type Conversion in C
24
C Input/Output
25
C Operators
26
C Functions
28
29
C Pointers
30
31
C Storage Classes
32
C Memory Management
33
C Preprocessor
34
C File Handling
35
Miscellaneous
36
C Interview Questions
37
38
DSA to DevelopmentCourse
39
40
Escape Sequence in C
41
42
The escape sequence in C is the characters or the sequence of characters that can be used
inside the string literal. The purpose of the escape sequence is to represent the characters
that cannot be used normally using the keyboard. Some escape sequence characters are the
part of ASCII charset but some are not.
43
44
Different escape sequences represent different characters but the output is dependent on
the compiler you are using.
45
46
47
48
49
50
51
\f Form Feed It is used to move the cursor to the start of the next logical page.
53
\n New Line It moves the cursor to the start of the next line.
54
\r Carriage Return It moves the cursor to the start of the current line.
55
\t Horizontal Tab It inserts some whitespace to the left of the cursor and moves the cursor
accordingly.
56
57
58
59
60
61
62
63
64
Out of all these escape sequences, \n and \0 are used the most. In fact, escape sequences
like \f, \a, are not even used by programmers nowadays.
65
66
67
The following are the escape sequence examples that demonstrate how to use different
escape sequences in C language.
68
69
70
71
72
73
74
75
76
77
•
78
79
80
81
82
83
84
85
86
87
"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");
88
89
90
10
91
92
93
Output
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
6
109
110
111
112
113
114
115
116
10
117
118
11
119
120
12
121
122
123
Output
124
125
Hi Geeks
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
7
142
143
144
145
146
147
148
Output
149
Hello
150
GeeksforGeeks
151
152
153
154
155
156
2
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
10
173
174
11
175
176
12
177
178
179
Output
180
Hello GFG
181
The escape sequence “\t” is very frequently used in loop-based pattern printing programs.
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
•
204
10
205
206
11
207
208
12
209
210
13
211
212
213
Output
214
215
Hello friends
216
Welcome to GFG
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
8
235
236
237
238
10
239
240
241
Output
242
243
GeeksforGeeks
244
245
246
247
248
249
2
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
10
266
267
11
268
269
12
270
271
272
Output
273
Hello\GFG
274
Explanation: It contains two ‘\’ which means we want print ‘\’ as output.
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
10
298
299
300
Output
301
302
303
304
305
306
307
308
309
310
311
312
4
313
314
315
316
317
318
319
320
321
322
323
324
10
325
326
11
327
328
12
329
330
13
331
332
333
Output
334
??!
335
336
337
338
339
340
341
342
343
344
4
345
346
347
348
349
350
351
352
353
354
355
char* s = "A\072\065";
356
10
357
358
11
359
360
12
361
362
363
Output
364
A:5
365
Explanation: Here 000 is one to three octal digits(0….7) means there must be at least one
octal digit after \ and a maximum of three. Here 072 is the octal notation, first, it is
converted to decimal notation which is the ASCII value of char ‘:’. At the place of \072, there
is: and the output is A:5.
366
367
368
369
370
371
372
373
374
3
375
376
377
378
379
380
381
382
383
384
385
386
387
char* s = "B\x4a";
388
10
389
390
11
391
392
12
393
394
395
Output
396
BJ
397
Explanation: Here hh is one or more hexadecimal digits(0….9, a…f, A…F). There can be more
than one hexadecimal number after \x. Here, ‘\x4a’ is a hexadecimal number and it is a
single char. Firstly it will get converted into decimal notation and it is the ASCII value of the
char ‘J’. Therefore at the place of \x4a, we can write J. So the output is BJ.
398
399
400
401
Escape Sequence in C
402
Visit Course
403
Master C programming with our C Programming Course Online, which covers everything
from the basics to advanced concepts like data s
405
406
407
408
409
410
411
412
char* s = "B\x4a";
413
414
415
Output
BJ
Explanation: Here hh is one or more hexadecimal digits(0….9, a…f, A…F). There can be more
than one hexadecimal number after \x. Here, ‘\x4a’ is a hexadecimal number and it is a
single char. Firstly it will get converted into decimal notation and it is the ASCII value of the
char ‘J’. Therefore at the place of \x4a, we can write J. So the output is BJ.
Arithmetic Operators in C
Arithmetic operators are the type of operators used to perform basic math operations like
addition, subtraction, and multiplication. Let’s take a look at an example:
1
Output
30
Explanation: In this code, the + operator is used for arithmetic addition, adding the
integers 10 and 20 resulting in value 30 which is stored in the variable sum.
The binary arithmetic operators work on two operands. C provides 5 such operators for
performing arithmetic functions which are as follows:
Example
1
2
res = a + b;
10
res = a - b;
11
12
13
14
res = a * b;
15
16
17
18
res = a / b;
19
20
21
22
res = a % b;
23
24
25
Output
a + b is 14
a - b is 6
a * b is 40
a / b is 2
a % b is 2
Note: All arithmetic operators can be used with float and int types except the modulo
operator that can only be used with integers.
The unary arithmetic operators work with a single operand. In C, we have four such
operators which are as follows:
Example
4
5
res = a++;
10
11
12
13
14
15
res = a--;
16
17
18
19
20
21
22
res = ++a;
23
24
25
26
27
28
29
30
res = --a;
31
32
33
34
35
36
37
38
39
Output
a is 11, res is 10
a is 10, res is 11
a is 11, res is 11
a is 10, res is 10
+a is 10
-a is -10
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
var = 10 * 20 + 15 / 5;
10
Output
203
This is due to the concept in C language where the operators with higher precedence will be
evaluated first. The operator precedence system helps to provide unambiguous expressions.
What is the difference between the unary minus and subtraction operators?
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.
No, the modulus operator (%) in C is only valid for integers. It cannot be used with floating-
point numbers like float or double. To find the remainder with floating-point numbers, you
can use the function from the math library.
In C, when both operands are integers, the division result is also an integer. The fractional
part is discarded during the division, resulting in integer division. To get a floating-point
result, at least one operand must be a float or double.
Unary operators in C
Unary operators are the operators that perform operations on a single operand to produce
a new value.
Unary minus ( – )
Increment ( ++ )
Decrement ( — )
NOT ( ! )
sizeof()
1. Unary Minus
The minus operator ( – ) changes the sign of its argument. A positive number becomes
negative, and a negative number becomes positive.
Unary minus is different from the subtraction operator, as subtraction requires two
operands.
10
11
12
13
14
Output
2. Increment
The is used to increment the value of the variable by 1. The increment can be done in two
ways:
In this method, the operator precedes the operand (e.g., ++a). The value of the operand will
be altered before it is used.
Example:
In this method, the operator follows the operand (e.g., a++). The value operand will be
altered after it is used.
Example:
9
10
11
12
3. Decrement
The is used to decrement the value of the variable by 1. The decrement can be done in two
ways:
In this method, the operator precedes the operand (e.g., – -a). The value of the operand will
be altered before it is used.
Example:
In this method, the operator follows the operand (e.g., a- -). The value of the operand will be
altered after it is used.
Example:
9
10
11
12
4. NOT ( ! )
The 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:
10
11
12
else
13
14
15
16
Output
a is greater than b
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:
7
8
10
11
12
Output
Address of a = 0x7fff78c3f37c
6. sizeof()
This operator returns the size of its operand, in bytes. The 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.
9
10
11
Output
Size of double: 8
Size of int: 4
Assignment Operators in C
Assignment operators are used for 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.
1. “=”: 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';
2. “+=”: 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:
4. “*=” 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:
5. “/=” 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:
9
10
11
12
13
14
15
16
a += 10;
17
18
19
20
21
a -= 10;
22
23
24
25
26
a *= 10;
27
28
29
30
31
a /= 10;
32
33
34
35
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
C Logical Operators
Logical NOT ( ! )
The logical AND operator (&&) returns true only if both operands are non-zero. Otherwise,
it returns false (0). The return type of the result is int. Below is the truth table for the logical
AND operator.
Syntax
Example
10
11
12
13
else {
14
15
16
17
Output
2. Logical OR Operator ( || )
The logical OR operator returns true if any one of the operands is non-zero. Otherwise, it
returns false i.e., 0 as the value. Below is the truth table for the logical OR operator.
Syntax
Example
10
if (a > 0 || b > 0) {
11
12
13
14
else {
15
16
17
18
Output
If the given operand is true then the logical NOT operator will make it false and vice-versa.
Below is the truth table for the logical NOT operator.
Syntax
Example
7
8
10
11
12
13
14
15
16
else {
17
18
19
20
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.
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
1
2
if (number > 0)
10
else
11
12
13
14
15
16
if (number % 2 == 0)
17
18
else
19
20
21
22
23
24
25
26
27
28
29
30
31
else {
32
33
34
35
36
37
38
39
40
41
42
else {
43
44
45
46
47
Output
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
2
3
if (number > 0)
10
11
else
12
13
14
15
16
17
18
if (number % 2 == 0)
19
20
else
21
22
23
24
25
26
27
28
29
30
31
if (is_positive(x) || is_even(x)) {
32
33
<< endl;
34
35
else {
36
37
38
39
40
41
42
43
if (is_positive(y) || is_even(y)) {
44
45
<< endl;
46
47
else {
48
49
50
51
52
Output
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.
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.
void main()
Answer:
4
5
else
Answer:
Coding
Bitwise Operators in C
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.
The & (bitwise AND) 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.
The | (bitwise OR) in 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.
The ^ (bitwise XOR) in 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.
The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and the
second operand decides the number of places to shift.
The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and the
second operand decides the number of places to shift.
The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
Bitwise operators allow precise manipulation of bits, giving you control over hardware
operations.
unsigned int a = 5, b = 9;
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Output
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 4294967290
b<<1 = 18
b>>1 = 4
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 are 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 for more details.
2. The bitwise OR of two numbers is simply the sum of those two numbers if there is no
carry involved; otherwise, you 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 ‘b’ 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 doing XOR to all numbers.
Example
Below program demonstrates the use XOR operator to find odd occcuring elements in an
array.
4
5
10
11
res ^= arr[i];
12
13
14
15
16
17
18
19
20
findOdd(arr, n));
21
22
Output
The following are many other interesting problems using the XOR operator.
.
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 & & && are different for the same operands.
Example
The below program demonstrates the difference between & and && operators.
8
9
10
11
12
Output
False True
5. The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.
Example:
The below example demonstrates the use of left-shift and right-shift operators.
10
11
Output
x << 1 = 38
x >> 1 = 9
6. 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.
Example
The below example demonstrates the use bitwise & operator to find if the given number is
even or odd.
Output
Odd
Example
unsigned int x = 1;
10
11
Output
Signed Result -2
Unsigned Result 4294967294
Related Articles
A r is an with a positive ‘+’ or negative sign ‘-‘ associated with it. Since the computer only
understands binary, it is necessary to represent these signed integers in binary form.
In the signed integer representation method the following rules are followed:
1. The MSB (Most Significant Bit) represents the sign of the Integer.
2. Magnitude is represented by other bits other than MSB i.e. (n-1) bits where n is the no. of
bits.
3. If the number is positive, MSB is 0 else 1.
4. The range of signed integer representation of an n-bit number is given as –(2^{n-1}-
1) to (2)^{n-1}-1.
Example:
Let n = 4
Range:
–(2^{4-1}-1) to 2^{4-1}-1
= -(2^{3}-1) to 2^{3}-1
= -(7) to+7
Drawbacks:
1. For 0, there are two representations: -0 and +0 which should not be the case as 0 is
neither –ve nor +ve.
2. Out of 2^n bits for representation, we are able to utilize only 2^{n-1} bits.
3. are not in cyclic order i.e. After the largest number (in this, for example, +7) the next
number is not the least number (in this, for example, +0).
4. For signed extension does not work.
Example:
Signed extension for +5
5. As we can see above, for +ve representation, if 4 bits are extended to 5 bits there is a need
to just append 0 in MSB.
6. But if the same is done in –ve representation we won’t get the same number. i.e. 10101 ≠
11101.
1. For +ve numbers the representation rules are the same as signed integer representation.
2. For –ve numbers, we can follow any one of the two approaches:
Write the +ve number in binary and take 1’s complement of it.
Example:
(-5) in 1’s complement:
+5 = 0101
-5 = 1010
3. The range of 1’s complement integer representation of n-bit number is given as –(2^{n-
1}-1) to 2^{n-1}-1.
Drawbacks:
For 0, there are two representations: -0 and +0 which should not be the case as 0 is neither
–ve nor +ve.
Out of 2^n bits for representation, we are able to utilize only 2^{n-1} bits.
1. Numbers are in cyclic order i.e. after the largest number (in this, for example, +7) the next
number is the least number (in this, for example, -7).
2. For negative number signed extension works.
3. As it can be seen above, for +ve as well as -ve representation, if 4 bits are extended to 5
bits there is a need to just append 0/1 respectively in MSB.
1. For +ve numbers, the representation rules are the same as signed integer representation.
2. For –ve numbers, there are two different ways we can represent the number.
Example:
(-5) in 4-bit representation
2^4-5=11 -→1011(unsigned)
Example:
(-5) in 2’s complement
(+5) = 0101
1’s complement of (+5) = 1010
Add 1 in 1010: 1010+1 = 1011
Therefore (-5) = 1011
Merits:
The range of numbers that can be represented using 2’s complement is very high.
Due to all of the above merits of 2’s complement representation of a signed integer, binary
numbers are represented using 2’s complement method instead of signed bit and 1’s
complement.
Operator precedence and associativity are rules that decide the order in which parts of an
expression are calculated. Precedence tells us which operators should be evaluated first,
while associativity determines the direction (left to right or right to left) in which operators
with the same precedence are evaluated.
1
2
res = a + b * c / 2;
10
11
12
13
Output
12
In this article, let’s discuss operator precedence, operator associativity, and the precedence
table that determines the priority of operators in expressions in C language.
Operator Precedence
Output
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. Let’s evaluate the
following expression,
100 / 5 % 2
The division (/) and modulus (%) operators have the same precedence, so the order in
which they are evaluated depends on their left-to-right associativity. This means the
division is performed first, followed by the modulus operation. After the calculations, the
result of the modulus operation is determined.
Output
Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions.
10
11
Output
90
The following tables list the C operator precedence from highest to lowest and the
associativity for each of the operators:
Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S REBL TAC
Important Points
There are a few important points and cases that we need to remember for operator
associativity and precedence which are as follows:
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.
x = 5;
10
11
12
13
14
x = 10;
15
16
17
18
19
20
21
22
Output
10
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
100 + 200 / 10 – 3 * 10
= 90
But if we enclose 100 + 200 in parenthesis, then the result will be different.
=0
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.
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.
Check article for more details.
Comma has the least precedence among all operators and should be used carefully.
a = 1, 2, 3;
10
Output
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”.
4
5
if (c > b > a)
10
11
else
12
13
Output
FALSE
Conclusion
It is necessary to know the precedence and associativity for the efficient usage of operators.
It allows us to write clean expressions by avoiding the use of unnecessary parenthesis. Also,
it is the same for all the C compilers so it also allows us to understand the expressions in the
code written by other programmers.
Also, when confused about or want to change the order of evaluation, we can always rely on
parenthesis ( ). The advantage of brackets is that the reader doesn’t have to see the table to
find out the order.