100% found this document useful (1 vote)
28 views

C_Programming_Theory_Only

The C Programming Language Tutorial provides a comprehensive overview of C, a general-purpose, procedural programming language developed by Dennis Ritchie in 1972, known for its simplicity, efficiency, and low-level memory access. The tutorial covers various topics including syntax, data types, control structures, and advanced concepts like pointers and memory management, aimed at helping beginners build a strong foundation in programming. It also discusses the features, applications, and standards of C, highlighting its importance in modern programming and its influence on other languages.

Uploaded by

amitkumar950925
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
28 views

C_Programming_Theory_Only

The C Programming Language Tutorial provides a comprehensive overview of C, a general-purpose, procedural programming language developed by Dennis Ritchie in 1972, known for its simplicity, efficiency, and low-level memory access. The tutorial covers various topics including syntax, data types, control structures, and advanced concepts like pointers and memory management, aimed at helping beginners build a strong foundation in programming. It also discusses the features, applications, and standards of C, highlighting its importance in modern programming and its influence on other languages.

Uploaded by

amitkumar950925
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 220

C Programming Language Tutorial

Last Updated : 06 Jan, 2025

C is a general-purpose, procedural, and middle-level programming language used for


developing computer software, system programming, applications, games, and more.
Known for its simplicity and efficiency, C is an excellent choice for beginners as it provides a
strong foundation in programming concepts. C was developed by Dennis M. Ritchie at Bell
Laboratories in 1972. Initially, it was created for programming the UNIX operating system.

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.

Hello World Program

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 Structures and Union

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.

The use of C is given below:

Operating Systems

Language Compilers

Assemblers

Text Editors

Print Spoolers

Network Drivers

Modern Programs

Databases

Language Interpreters

Utilities

FAQs

1. How to learn C easily?

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

Loops and Errors

Arrays and Strings

Pointers and Memory

Functions
Structures

Recursions

2. Difference between C and C++?

3. Is C easy to learn for beginners?

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#.

4. Why should we learn C first rather than C++?

C is a ‘mother of all languages.’ It provides a solid understanding of fundamental


programming concepts and is considered easier to grasp. C offers versatile applications,
from software development to game programming, making it an excellent choice for
building a strong programming foundation. C Language
Introduction

Last Updated : 10 Jan, 2025

C is a procedural programming language initially developed by Dennis Ritchie in the


year 1972 at Bell Laboratories of AT&T Labs. It was mainly developed as a system
programming language to write the UNIX operating system.

The main features of the C language include:

General Purpose and Portable

Low-level Memory Access

Fast Speed

Clean Syntax

These features make the C language suitable for system programming like an operating
system or compiler development.

Why Should We Learn C?


Many later languages have borrowed syntax/features directly or indirectly from the C
language like the syntax of Java, PHP, JavaScript, and many other languages that are mainly
based on the C language. C++ is nearly a superset of C language (Only a few programs may
compile in C, but not in C++).

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.

Difference Between C and C++

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.

C++ has exception handling capabilities. In C, we have to resolve exceptions manually.

There are no references in C.

There are many more differences between C and C++ which are discussed here:

Beginning with C Programming

Writing the First Program in C

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

Let us analyze the structure of our program line by line.

Structure of the C program

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:

1. Header Files Inclusion – Line 1 [#include <stdio.h>]

The first and foremost component is the inclusion of the Header files in a C program. A
header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. All lines that start with # are
processed by a 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:

stddef.h – Defines several useful types and macros.

stdint.h – Defines exact width integer types.

stdio.h – Defines core input and output functions

stdlib.h – Defines numeric conversion functions, pseudo-random number generator, and


memory allocation

string.h – Defines string handling functions

math.h – Defines common mathematical functions.

2. Main Method Declaration – Line 2 [int main()]

The next part of a C program is to declare the main() function. It is the entry point of a C
program and the execution typically begins with the first line of the main(). The empty
brackets indicate that the main doesn’t take any parameter (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.

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

The body of a function in the C program refers to statements that are a part of that function.
It can be anything like manipulations, searching, sorting, printing, etc. A pair of curly
brackets define the body of a function. All functions must start and end with curly brackets.

4. Statement – Line 4 [printf(“Hello World”);]

Statements are the instructions given to the compiler. In C, a statement is always terminated
by a semicolon (;). In this particular case, we use printf() function to instruct the compiler to
display “Hello World” text on the screen.

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

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

How to Execute the Above Program?

In order to execute the above program, we need to first compile it using a compiler and then
we can run the generated executable. There are online IDEs available for free 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.

Embedded systems: C is a popular language for developing embedded systems such as


microcontrollers, microprocessors, and other electronic devices.
System software: C is used for developing system software such as device drivers,
compilers, and assemblers.

Networking: C is widely used for developing networking applications such as web servers,
network protocols, and network drivers.

Database systems: C is used for developing database systems such as Oracle, MySQL, and
PostgreSQL.

Gaming: C is often used for developing computer games due to its ability to handle low-level
hardware interactions.

Artificial Intelligence: C is used for developing artificial intelligence and machine learning
applications such as neural networks and deep learning algorithms.

Scientific applications: C is used for developing scientific applications such as simulation


software and numerical analysis tools.

Financial applications: C is used for developing financial applications such as stock market
analysis and trading systems.

Features of C Programming Language

Last Updated : 10 Jan, 2025

C is a procedural programming language. It was initially developed by Dennis Ritchie in the


year 1972. It was mainly developed as a system programming language to write an
operating system.

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.

What are the Most Important Features of C Language?

Here are some of the most important features of the C language:

Procedural Language

Fast and Efficient

Modularity
Statically Type

General-Purpose Language

Rich set of built-in Operators

Libraries with Rich Functions

Middle-Level Language

Portability

Easy to Extend
1. Procedural Language

In a like C step by step, predefined instructions are carried out. C program may contain
more than one function to perform a particular task. New people to programming will think
that this is the only way a particular programming language works. There are other
programming paradigms as well in the programming world. Most of the commonly used
paradigm is an object-oriented programming language.

2. Fast and Efficient

Newer languages like Java, python offer more features than 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

C programming language is a . Meaning the type of variable is checked at the time of


compilation but not at run time. This means each time a programmer types a program they
have to mention the type of variables used.

5. General-Purpose Language

From system programming to photo editing software, the C programming language is used
in various applications. Some of the common applications where it’s used are as follows:

: Windows, , iOS, , OXS


: PostgreSQL, Oracle, , MS SQL Server, etc.

6. Rich set of built-in Operators

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

7. Libraries with Rich Functions

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

8. Middle-Level Language

As it is a middle-level language so it has the combined form of both capabilities of assembly


language and features of the .

9. Portability

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

10. Easy to Extend

Programs written in C language can be extended means when a program is already written
in it then some more features and operations can be added to it.

Let discuss these features one by one:

C Programming Language Standard

Last Updated : 24 Jan, 2025

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.

C99 (ISO/IEC 9899:1999) introduced several new features, including variable-length


arrays, flexible array members, complex numbers, inline functions, and designated
initializers. This standard also includes several new library functions and updates to
existing ones.

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.

Security vulnerabilities: C programs are prone to security vulnerabilities, such as buffer


overflows, if not written carefully.
Overall, C is a powerful language with many advantages, but it also requires a high degree of
expertise to use effectively and has some potential drawbacks, especially for beginners or
developers working on complex projects.

Importance:

important for several reasons:

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.

Avoiding common pitfalls: Understanding the potential disadvantages of C, such as memory


management issues or security vulnerabilities, can help developers avoid common pitfalls
and write safer, more secure code.

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.

The idea of this article is to introduce C standard.

What to do when a C program produces different results in two different compilers?


For example, consider the following simple C program.

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.

2 1 3 - using g++ 4.2.1 on Linux.i686


1 2 3 - using SunStudio C++ 5.9 on Linux.i686
2 1 3 - using g++ 4.2.1 on SunOS.x86pc
1 2 3 - using SunStudio C++ 5.9 on SunOS.x86pc
1 2 3 - using g++ 4.2.1 on SunOS.sun4u
1 2 3 - using SunStudio C++ 5.9 on SunOS.sun4u

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.

Can we know the behavior of all programs from C standard?


C standard leaves some behavior of many C constructs as and some as to simplify the
specification and allow some flexibility in implementation. For example, in C the use of any
automatic variable before it has been initialized yields undefined behavior and order of
evaluations of subexpressions is unspecified. This specifically frees the compiler to do
whatever is easiest or most efficient, should such a program be submitted.
So what is the conclusion about above two examples?
Let us consider the first example which is “void main() {}”, the standard says following
about prototype of main().

The function called at program startup is named main. The implementation


declares no prototype for this function. It shall be defined with a return
type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names
may be used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.

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.

The order in which the function designator, arguments, and


subexpressions within the arguments are evaluated in a function
call (6.5.2.2).

What to do with programs whose behavior is undefined or unspecified in standard?


As a programmer, it is never a good idea to use programming constructs whose behavior is
undefined or unspecified, such programs should always be discouraged. The output of such
programs may change with the compiler and/or machine.

Setting Up C Development Environment

Last Updated : 19 Dec, 2023

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.

Using Onlinе IDE

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.

An example is the on-line IDE provided by GееksforGееks at .

Output

Learning C at GeekforGeeks

Time Complexity: O(1)


Auxiliary Space: O(1)

Setting up a Local Environmеnt

For a comprehensive C development environment on your local machine, two fundamental


components are necessary: a compiler and a text editor.

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:

sudo apt-get update

sudo apt-get install gcc

sudo apt-get install g++

B. Additionally, you can install the build-essential package, which includes essential
libraries for compiling and running C programs:

sudo apt-get install build-essential

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:

gcc filename.c -o any-name

G. After executing the above command, a new file with the name you chose as "any-name"
will be created in the same directory.

H. To run your program, use the following command:

./hello

I. This command will execute your program in the terminal window.

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.

Before embarking on C programming, it is imperative to have a text editor installed for


writing programs. Follow the instructions below to install popular code editors such as VS
Code and Code::Blocks on different operating systems like Windows, Mac OS, etc.

1. Codе::Blocks Installation

Download Code::Blocks by selecting the setup package based on your OS from .

Open the downloaded Code::Blocks setup file.

Follow the on-screen instructions for installation.

After successfully installing Code::Blocks, open the application.

Navigate to the File menu.

Select "New" and choose "Empty file."

In the newly created empty file, write your C program.

Save the file with a '.c' extension.

Go to the Build menu in Code::Blocks.

Choose the "Build and Run" option.

2. For Mac Users: Setting Up Xcode as a Code Editor

Step 1: Download and Install Xcode:

Visit the or search for Xcode on the Apple App Store.

Follow the link for download and installation instructions.

Step 2: Open Xcode:

After successfully installing Xcode, open the Xcode application.

Step 3: Create a New Project:

To create a new project, go to the File menu.


Select "New" and choose "Project." This will generate a new project for you.

Step 4: Choose Project Template:

In the next window, choose a template for your project.

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.

Step 5: Provide Project Details:

In the following window, provide necessary details like organization name, Product Name,
etc.

Ensure you choose the language as C++.

After filling in the details, click the Next button to proceed.

Step 6: Select Project Location:

Choose the location where you want to save your project.

Step 7: Choose Main C File:

Select the main.c file from the directory list on the left sidebar.

Step 8: Modify or Run Your Program:

After opening the main.c file, you'll see a pre-written C program or template.

Modify the program as per your requirements.

To run your C program, go to the Product menu and choose the Run option from the
dropdown.

VS Code Installation With C

3. Installing VS Codе on Windows

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.

Download MinGW from .

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".

4. Installing VS Codе on Mac OS

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:

arch -x86_64 ruby -e "$(curl -fsSL


https://raw.githubusercontent.com/Homebrew/install/HEAD/install)" < /dev/null 2>
/dev/null

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.

arch -x86_64 brew install MinGW-w64

This is also a timе-taking process, so bе patiеnt!

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.

C Hello World Program

Last Updated : 14 Jan, 2025

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.

C Program to Print “Hello World”

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

Compiling a C Program: Behind the Scenes

Last Updated : 10 Jan, 2025

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.

The C program goes through the following phases during compilation:

Compilation Process in C

Understanding the compilation process in C helps developers optimize their programs.

How do we compile and run a C program?

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.

Step 1: Creating a C Source File

We first create a C program using an editor and save the file as filename.c

$ vi filename.c

We can write a simple hello world program and save it.

Step 2: Compiling using GCC compiler

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.

Step 3: Executing the program

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.

What goes inside the compilation process?

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.

$gcc -Wall -save-temps filename.c –o filename

The following screenshot shows all generated intermediate files.

Intermediate Files

Let us one by one see what these intermediate files contain.


1. Pre-processing

This is the first phase through which source code is passed. This phase includes:

Removal of Comments

Expansion of Macros

Expansion of the included files.

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.

Comments are stripped off.

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.

Assembly Code File

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

Last Updated : 21 Jan, 2025

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.

Colon(:): It is an operator that essentially invokes something called an initialization list.

Semicolon(;): It is known as a statement terminator. It indicates the end of one logical


entity. That’s why each individual statement must be ended with a semicolon.

Asterisk (*): 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.

Period (.): Used to access members of a structure or union.

Tilde(~): Bitwise One’s Complement Operator.

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:

int, for, if, else, while, return, etc.

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:

char str[] = "Hello, World!";

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

const int MAX_VALUE = 100;

Output

100

C Identifiers

Last Updated : 20 Jan, 2025

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() {}

In the above code snippet, “val” and “func” are identifiers.

Rules for Naming Identifiers in C

A programmer must follow a set of rules to create an identifier in C:

Identifier can contain following characters:

Uppercase (A-Z) and lowercase (a-z) alphabets.

Numeric digits (0-9).

Underscore (_).
The first character of an identifier must be a letter or an underscore.

Identifiers are case-sensitive.

Identifiers cannot be keywords in C (such as int, return, if, while etc.).

The below image and table show some valid and invalid identifiers in C language.

Examples of Identifiers

The following examples demonstrate the creation and usage of identifiers in C:

Creating an Identifier for a Variable

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.

Creating an Identifier for a Function

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:

What happens if we use a keyword as an Identifier 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':

./Solution.c:5:14: error: expected identifier or '(' before '=' token

Keywords in C

Last Updated : 10 Jan, 2025

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.

What are Keywords?

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.

auto int num;

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

auto int a = 10;

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

switch, case, and default

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
}

Below is the C program to demonstrate the switch case statement:

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 keyword in C is used to declare a character variable in the C programming language.

char x = 'D';

Below is the C program to demonstrate the char keyword:

char c = 'a';

9
10

Output

const

The const keyword defines a variable who’s value cannot be changed.

const int num = 10;

Below is the C program to demonstrate the const keyword:

const int a = 11;

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:

error: assignment of read-only variable 'a'


a = a + 2;
do

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.

Below is the C program to demonstrate a do-while loop.

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 marks = 97.5;


double num;

Below is the C program to demonstrate double float keyword:

float f = 0.3;

double d = 10.67;

10

11

12

Output

Float value: 0.300000

Double value: 10.670000


if-else

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
}

Below is the C program to demonstrate an if-else statement:

if(a < 11)

10

11

12

13

else

14

15
16

"greater than 11");

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.

Below is the C program to demonstrate a for-loop:

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:

Below is the C program to demonstrate the goto keyword:

void printNumbers() {

10

label:

11

12

n++;

13

if (n <= 10) goto label;

14

15

16
17

18

printNumbers();

19

20

Output

1 2 3 4 5 6 7 8 9 10

int

Example:

Below is the C program to show the int keyword:

void sum() {

sum = a + b;

10

11
12

13

14

sum();

15

16

Output

30

short, long, signed, and unsigned

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:

short int a = 12345;

10
11

12

signed int b = -34;

13

14

15

unsigned int c = 12;

16

17

18

19

long int d = 99998L;

20

21

22

23

24

25

26

Output

Integer value with a short int data: 12345

Integer value with a signed int data: -34


Integer value with an unsigned int data: 12

Integer value with a long int data: 99998

The return statement returns a value to where the function was called.

Example:

Below is the C program to demonstrate the return keyword:

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.

Below is the C program to demonstrate sizeof keyword:

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:

register char c = 's';

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:

static int num;

struct

The struct keyword in C programming language is used to declare a structure. A structure is


a list of variables, (they can be of different data types), which are grouped together under
one data type.

For Example:

Below is the C program for the struct keyword:

char title[50];

char author[50];

10
11

12

13

14

15

16

17

strcpy(book1.title, "C++ Programming");

18

strcpy(book1.author, "Bjarne Stroustrup");

19

20

21

22

23

24

Output

Book 1 title : C++ Programming

Book 1 author : Bjarne Stroustrup

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:

Below is the C program for the union keyword:

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:

const volatile marks = 98;

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 are Reserved words in C with certain meanings.

We can’t use keywords as any element’s name.

There are 32 keywords in C all having unique meanings.

Keywords in C – FAQs

What are keywords in C?

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.

How many keywords are there in the C language?

There are 32 keywords in the C language.

What is the sizeof keyword in C?

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.

What is volatile in c used for?

Volatile keywords in C are used for volatile objects.

Difference between keywords and identifiers.

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

Last Updated : 17 Jan, 2025

The comments in C are human-readable explanations or notes in the source code of a C


program. A comment makes the program easier to read and understand. These are the
statements that are not executed by the compiler or an interpreter.

Example:

Output
Hello

In C there are two types of comments in C language:

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

This comment contains some code which

will not be executed.

*/

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

This line will cause an error because the compiler

considers the above '*/' as the end of the comment block.

*/

10

11

Output

./Solution.c: In function 'main':


./Solution.c:6:8: error: unknown type name 'This'
This line will cause an error because the compiler
^
./Solution.c:6:18: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'will'
This line will cause an error because the compiler
^

If nested comments are needed, it’s best to use single-line comments or comment out
individual parts.

4
5

10

11

Try it on GfG Practice

Output

Program runs without errors.

Best Practices for Writing Comments

Following are some best practices to write comments in your program:

Write comments that are easy to understand.

Do not comment on every line unnecessarily and avoid writing obvious comments.

Update comments regularly.

Focus on explaining the intent behind the code rather than restating the obvious.

C Variables

Last Updated : 21 Jan, 2025


In C, variable is a name given to the memory location that helps us to store some form of
data and retrieves it when required. It allows us to refer to memory location without having
to memorize the memory address. A variable name can be used in expressions as a
substitute in place of the value it stores.

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:

data_type v1, v2, v3 ….;

where v1, v2 … are the names for variables.

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;

It can also be combined with variable definition:

data_type variable_name; = value;

Variable Syntax Breakdown

Example of Variable

5
6

10

age = 18;

11

12

13

14

15

16

char math, physics, chemistry, arts, sports;

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

Rules for Naming Variables in C

We can assign any name to the variable as long as it follows the following rules:

A variable name must only contain alphabets, digits, and underscore.

A variable name must start with an alphabet or an underscore only. It cannot start with a
digit.

No white space is allowed within the variable name.

A variable name must not be any reserved word or keyword.


Also, it is recommended to use such a name for a variable that depicts its purpose.

C Variables – FAQs

Can a variable name in C start with a number?

No, variable names in C must begin with a letter or an underscore. Starting with a number is
not allowed.

What happens if you use an uninitialized variable in C?

Using an uninitialized variable in C leads to undefined behaviour, as it contains garbage data


until explicitly assigned a value.

Can i store different type of data in different type of variable?

No, you cannot store different type of data in a variable of different type.

Is it possible to change the type of a variable after it is declared?

No, once a variable is declared with a type in C, its type cannot be changed.

Constants in C

Last Updated : 10 Jan, 2025

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?

As the name suggests, a constant in C is a variable that cannot be modified once it is


declared in the program. We can not make any change in the value of the constant variables
after they are defined.

How to Define Constant in C?


We define a constant in C language using the const keyword. Also known as a const type
qualifier, the const keyword is placed at the start of the variable declaration to declare that
variable as a constant.

Syntax to Define Constant

const data_type var_name = value;

Example of Constants in C

const int int_const = 25;

10

11

const char char_const = 'A';

12

13
14

const float float_const = 15.66;

15

16

17

int_const);

18

19

char_const);

20

21

float_const);

22

23

24

Output

Printing value of Integer Constant: 25

Printing value of Character Constant: A

Printing value of Float Constant: 15.660000

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

Floating Point Constant

Double Precision Floating Point 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:

1. Initialization with Declaration

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

const int var;

10

var = 20;

11

12

13

14

Output

In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^

Difference Between Constants and Literals

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:

Defining Constant using #define Preprocessor

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.

Example of Constant Macro

3
4

10

Output

The value of pi: 3.14

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

Q1. Define C Constants.

Answer:

Constants in C are the immutable variables whose values cannot be modified once they are
declared in the C program.

Q2. What is the use of the const keyword?’

Answer:

The const keyword is the qualifier that is used to declare the constant variable in C
language.

Q3. Can we initialize the constant variable after the declaration?

Answer:

No, we cannot initialize the constant variable once it is declared.

Q4. What is the right way to declare the constant in C?

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:

Q6. Is there any way to change the value of a constant variable 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.

const int var = 10;

10

11

12
int* ptr

13

= (int*)&var; // explicit cast to remove constness

14

15

*ptr = 500;

16

17

18

19

20

Output

Initial Value of Constant: 10

Final Value of Constant: 500

Accessing through pointer: 500

Related Article –

Data Types in C

Last Updated : 10 Jan, 2025

Each variable in C has an associated data type. It specifies the type of data that the variable
can store like integer, character, floating, double, etc. Each data type requires different
amounts of memory and has some specific operations which can be performed over it.

The data types in C can be classified as follows:


Understanding C’s data types is critical for writing efficient programs.

The following are some main primitive data types in C:

Table of Content

Integer Data Type

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.

Range: -2,147,483,648 to 2,147,483,647

Size: 4 bytes

Format Specifier: %d

Syntax of Integer

We useto declare the integer variable:

The integer data type can also be used as

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

long int d = 99998L;

17

18

19

20
21

c);

22

23

24

25

Output

Integer value with positive data: 9

Integer value with negative data: -9

Integer value with an unsigned int data: 89

Integer value with an long int data: 99998

Character Data Type

Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.

Range: (-128 to 127) or (0 to 255)

Size: 1 byte

Format Specifier: %c

Syntax of char

The char keyword is used to declare the variable of character type:

char var_name;

Example of char

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 a after increment is: b

Value of c: c

Float Data Type

In C programming is used to store floating-point values. Float in C is used to store decimal


and exponential values. It is used to store decimal numbers (numbers with floating point
values) with single precision.

Range: 1.2E-38 to 3.4E+38

Size: 4 bytes

Format Specifier: %f

Syntax of float

The float keyword is used to declare the variable as a floating point:

float var_name;

Example of Float

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

Double Data Type

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.

Range: 1.7E-308 to 1.7E+308

Size: 8 bytes

Format Specifier: %lf

Syntax of Double

The variable can be declared as double precision floating point using the double keyword:

double var_name;

Example of Double

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

Void Data Type

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

Syntax:

Example of Void

4
5

void* ptr = &val;

10

11

Output

30

Size of Data Types in C

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

Example

8
9

10

11

12

13

14

size_of_char);

15

16

size_of_float);

17

18

size_of_double);

19

20

21

Output

The size of int data type : 4

The size of char data type : 1

The size of float data type : 4

The size of double data type : 8

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.

Data Type Modifiers in C

Last Updated : 17 Jan, 2025

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.

Let’s take a look at an example:

unsigned int ui = -100;

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.

In C, we have 4 data type modifiers:

Table of Content

Let’s understand each of them one by one.

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

Size of short int: 2

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

long int long_num;

long long int long_long_num;

8
9

double dub_num;

10

long double long_dub_num;

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

unsigned int n1 = 4294967296;

unsigned long int n2 = 4294967296;

10
11

12

13

Output

Unsigned int (n1): 0

Unsigned long int (n2): 4294967296

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

signed int n2 = 23124;

10
11

Output

Size and Range of Data Types with Modifiers

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

Last Updated : 22 Jan, 2025

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.

Let’s take a look at an example:

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

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;

float result = n1 + n2;

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.

When Implicit Type Conversion Occurs?


Some of its few occurrences are mentioned below:

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.

Conversions in Assignment Expressions:


Occurs when a value is assigned to a variable of a different type, e.g., assigning a float to an
int results in truncation of the decimal part.

Conversion in Other Binary Expressions:


Happens when operators are used on operands of different types. The compiler converts
them to a common type for compatibility (e.g., adding an int to a float).

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

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.

C Type Conversion – FAQ’s

What happens if I try to assign a double to an int without casting?

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.

Can I convert a float to a char safely in C?

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

In C language, operators are symbols that represent operations to be performed on one or


more operands. They are the basic components of the C programming. In this article, we will
learn about all the built-in operators in C with examples.

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:

Example of C Arithmetic Operators

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.

These are a total of 6 relational operators in C:

Example of C Relational Operators

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

Here, 0 means false and 1 means true.

3. Logical Operator in C

Logical Operators are used to combine two or more conditions/constraints or to


complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a Boolean value either true or false.
Example of Logical Operators 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.

There are 6 bitwise operators in C:

Example of Bitwise Operators

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.

In C, there are 11 assignment operators :

Example of C Assignment 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

sizeof is much used in the C programming language.

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)

To know more about the topic refer to article.

Comma Operator ( , )

The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).

The comma operator has the lowest precedence of any C operator.

Comma acts as both operator and separator.

Syntax

operand1 , operand2

To know more about the topic refer to article.

Conditional Operator ( ? : )

The conditional operator is the only ternary operator in C++.

Here, Expression1 is the condition to be evaluated. If the condition(Expression1)


is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of Expression3.
We may replace the use of if..else statements with conditional operators.

Syntax

operand1 ? operand2 : operand3;

To know more about the topic refer to article.

dot (.) and arrow (->) Operators

Member operators are used to reference individual members of classes, structures, and
unions.

The dot operator is applied to the actual object.

The arrow operator is used with a pointer to an object.

Syntax

structure_variable . member;

and

structure_pointer -> member;

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

To know more about the topic refer to article.

addressof (&) and Dereference (*) Operators


Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.

The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.

To know more about the topic refer to article.

Example of Other C Operators

int* add_of_num = &num;

10

11

12

13

14

15

16
17

Output

sizeof(num) = 4 bytes

&num = 0x7ffe2b7bdf8c

*add_of_num = 10

Unary, Binary and Ternary Operators in C

Operators can also be classified into three types on the basis of the number of operands
they work on:

Unary Operators: Operators that work on single operand.

Binary Operators: Operators that work on two operands.

Ternary Operators: Operators that work on three operands.

Operator Precedence and Associativity in C

In C, it is very common for an expression or statement to have multiple operators and in


these expression, there should be a fixed order or priority of operator evaluation to avoid
ambiguity.

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:

Operators are symbols used for performing some kind of operation in C.

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

Q1. What are operators in C?

Answer:

Operators in C are certain symbols in C used for performing certain mathematical,


relational, bitwise, conditional, or logical operations for the user.

Q2. What are the 7 types of operators in C?

Answer:

There are 7 types of operators in C as mentioned below:

Unary operator

Arithmetic operator

Relational operator

Logical operator

Bitwise operator

Assignment operator

Conditional operator

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.

Q4. What is the difference between prefix and postfix operators in C?

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

Q5. What is the Modulo operator?

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

Basic Input and Output in C

Last Updated : 14 Jan, 2025

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.

Standard Output Function – printf()

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.

Variable values and direct values(literals) can also be printed by printf().

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.

Standard Input Function – scanf()

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:

Enter your age: 25 (Entered by the user)

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.

Last Updated : 16 Jan, 2025

In C language, printf() function is used to print formatted output to the standard


output stdout (which is generally the console screen). The printf function is the most used
output function in C and it allows formatting the output in many ways.

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

The printf() function is defined inside <stdio.h> header file.

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.

args…: These are the variable/values corresponding to the format specifier.

Return Value:
Returns the number of characters printed after successful execution.

If an error occurs, a negative value is returned.

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.

Format Specifier in printf

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.

Breakdown of Format Specifier

%[flags][width][.precision][length]specifier

1. Specifier

It is the character that denotes the type of data. Some commonly used specifiers are:

%d: for printing integers

%f: for printing floating-point numbers

%c: for printing characters

%s: for printing strings

%%: Prints '%' literal

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.

For String (s): Specifies the length of the string to be printed.

4. Length

Specifies the length of the data type in the memory. It is used in correspondence with

There are 3 length sub-specifiers:

h: With short int and unsigned short int

l: With long int and unsigned long int.

L: With long double

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

The sum of 99 and 1 is 100

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

Sum of 99 and 1 is 100

Explanation: The format specifier %d is used to print integer literals. It substitutes 99, 1,
and the result of 99 + 1 into the string.

Right Align the Output

We can right align the output using the width specifier with positive value.

2
3

char s[] = "Welcome to GfG!";

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.

Left Align the Output with Specified Width

If we pass negative width, the minimum width will be the absolute value of the width, but
the text will be left aligned.

char s[] = "Welcome to GfG!";

5
6

10

Output

Welcome to GfG! Geeks

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.

Add Leading Zeroes to Integer

The precision sub-specifier adds leading zeroes to the integer.

Output

For integers: 0000002451


For floats: 12.45

For strings: Geeks

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.

Limit Digits After Point in Float

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.

Limit Number of Characters in a String

For strings, precision limits the number of characters to be printed.


1

char s[] = "Welcome to GfG!";

Output

Welcome

Last Updated : 11 Oct, 2024

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.

The syntax of scanf() in C is similar to the syntax of printf().

Here,

int is the return type.

format is a string that contains the format specifiers(s).


“…” indicates that the function accepts a variable number of arguments.

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 format specifiers recognized by scanf:

%d to accept input of integers.

%ld to accept input of long integers

%lld to accept input of long long integers

%f to accept input of real number.

%c to accept input of character types.

%s to accept input of a string.

To know more about format specifiers, refer to this article –

Example:

The scanf will write the value input by the user into the integer variable var.

Return Value of scanf

The scanf in C returns three types of values:

>0: The number of values converted and assigned successfully.

0: No value was assigned.

<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.

& is also called as address of the operator.

For example, &var is the address of var.

Example of scanf

Below is the C program to implement scanf:


1

10

11

12

13

14

15

16

17

a , b);

18

19

20
Output

Enter first number: 5


Enter second number: 6
A:5 B:6

Related Article:

. Format Specifiers in C

Last Updated : 10 Jan, 2025

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.

List of Format Specifiers in C

The below table contains the most commonly used format specifiers in C

Examples of Format Specifiers in C

1. Character Format Specifier – %c 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:

Enter some character: A

Output:

The entered character: A

2. Integer Format Specifier (signed) – %d in C

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:

Enter the integer: 45

Output:

Printed using %d: 45


Printed using %i: 45

3. Unsigned Integer Format Specifier – %u in C

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:

Example: The following C Program demonstrates how to use %u in C.

unsigned int var;


Input:

Enter an integer: 25

Output:

Entered unsigned integer: 25


Printing -10 using %u: 4294967286

4. Floating-point format specifier – %f in C

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

Using %f: 12.670000

Using %e: 1.267000e+01

Using %E, 1.267000E+01

5. Unsigned Octal number for integer – %o in C

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

6. Unsigned Hexadecimal for integer – %x in C

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

7. String Format Specifier – %s in C

The %s in C is used to print strings or take strings as input.

Syntax:

Example:

char a[] = "Hi Geeks";

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

Enter the string: Hi Geeks

Output

Hi

As we can see, the string is only scanned till a whitespace is encountered. We can avoid that
by using .

8. Address Format Specifier – %p in C

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

The Memory Address of a: 0x7ffe9645b3fc

Input and Output Formatting

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 minus(-) sign tells left alignment.

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.

A period( . ) symbol separates field width with precision.

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.

Example of I/O Formatting

char str[] = "geeksforgeeks";

8
9

10

11

Output

geeksforgeeks

geeksforgeeks

geeks

geeks

Format Specifiers in C – FAQs

Does C have a format specifier for binary numbers?

No, the C language does not provide a format specifier for binary numbers.

What is the formatted string?

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

Last Updated : 10 Jan, 2025

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.

Escape Sequence List

The table below lists some common escape sequences in C language.


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.

Escape Sequence in C Examples

The following are the escape sequence examples that demonstrate how to use different
escape sequences in C language.

1. Example to demonstrate how to use \a escape sequence in C

"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");

10

Output

My mobile number is 7873923408

2. Example to demonstrate how to use \b escape sequence in C

3
4

10

11

12

Output

Hi Geeks

3. Example to demonstrate how to use \n escape sequence in C

Output

Hello
GeeksforGeeks

4. Example to demonstrate how to use \t escape sequence in C

10

11

12

Output

Hello GFG

The escape sequence “\t” is very frequently used in loop-based

5. Example to demonstrate how to use \v escape sequence in C

4
5

10

11

12

13

Output

Hello friends
Welcome to GFG

6. Example to demonstrate how to use \r escape sequence in C

9
10

Output

GeeksforGeeks

7. Example to demonstrate how to use \\ escape sequence in C

10

11

12

Output

Hello\GFG

Explanation: It contains two ‘\’ which means we want print ‘\’ as output.

8. Example to demonstrate how to use \’ and \” escape sequence in C

2
3

10

Output

' Hello Geeks

" Hello Geeks

9. Example to demonstrate how to use \? escape sequence in C

10

11

12
13

Output

??!

10. Example to demonstrate how to use \ooo escape sequence in C

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.

11. Example to demonstrate how to use \xhh escape sequence in C


1

C Preprocessors

C File Handling

C Programs

C Cheatsheet

C Interview Questions

C MCQ

C++

10

11

GfG Courses @90% Refund

12

Share Your Experiences

13

C Programming Language Tutorial


14

C Basics

15

C Variables and Constants

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 Control Statements Decision-Making


27

C Functions

28

C Arrays & Strings

29

C Pointers

30

C User-Defined Data Types

31

C Storage Classes

32

C Memory Management

33

C Preprocessor

34

C File Handling

35

Miscellaneous

36

C Interview Questions

37

Top 50 C Coding Interview Questions and Answers (2025)

38

DSA to DevelopmentCourse

39
40

Escape Sequence in C

41

Last Updated : 10 Jan, 2025

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

Escape Sequence List

47

The table below lists some common escape sequences in C language.

48

49

Escape Sequence Name Description

50

\a Alarm or Beep It is used to generate a bell sound in the C program.

51

\b Backspace It is used to move the cursor one place backward.


52

\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

\v Vertical Tab It is used to insert vertical space.

57

\\ Backlash Use to insert backslash character.

58

\’ Single Quote It is used to display a single quotation mark.

59

\” Double Quote It is used to display double quotation marks.

60

\? Question Mark It is used to display a question mark.

61

\ooo Octal Number It is used to represent an octal number.

62

\xhh Hexadecimal Number It represents the hexadecimal number.

63

\0 NULL It represents the NULL character.

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

Escape Sequence in C Examples

67

The following are the escape sequence examples that demonstrate how to use different
escape sequences in C language.

68

69

1. Example to demonstrate how to use \a escape sequence in C

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

My mobile number is 7873923408

95

2. Example to demonstrate how to use \b escape sequence in C

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

3. Example to demonstrate how to use \n escape sequence in C

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

4. Example to demonstrate how to use \t escape sequence in C

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

5. Example to demonstrate how to use \v escape sequence in C

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

6. Example to demonstrate how to use \r escape sequence in C

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

7. Example to demonstrate how to use \\ escape sequence in C

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

8. Example to demonstrate how to use \’ and \” escape sequence in C

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

' Hello Geeks

302

" Hello Geeks

303

9. Example to demonstrate how to use \? escape sequence in C

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

10. Example to demonstrate how to use \ooo escape sequence in C

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

11. Example to demonstrate how to use \xhh escape sequence in C

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

explore course icon


404

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

Last Updated : 21 Jan, 2025

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.

C provides 9 arithmetic operators to work with numbers and perform different


mathematical operations. These can be classified into two types based on the number of
operands they work on:

Binary Arithmetic Operators

Unary Arithmetic Operators

1. Binary Arithmetic Operators

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.

2. Unary Arithmetic Operators

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

Explanation: In this C program, the post-increment and post-decrement operators are


demonstrated, where the value of a is updated after it is assigned to res. In contrast, the pre-
increment and pre-decrement operators update a first before assigning it to res. The
program prints the value of a and res after each operation to show how the operators affect
the values of the variables.

Multiple Operators in a Single Expression

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

Example

var = 10 * 20 + 15 / 5;

10

Output
203

Explanation: The order of evaluation of the given expression is : ( ( 10 * 20 ) + (15 / 5 ) ).

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.

C Arithmetic Operators – FAQs

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.

Can the modulus operator be used with floating-point numbers?

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.

Why does 5 / 2 return 2 and not 2.5 in C?

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

Last Updated : 10 Jan, 2025

Unary operators are the operators that perform operations on a single operand to produce
a new value.

Types of unary operators

Types of unary operators are mentioned below:

Unary minus ( – )

Increment ( ++ )

Decrement ( — )
NOT ( ! )

Addressof operator ( & )

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.

Below is the implementation of the unary minus (-) operator:

10

11

12

13

14
Output

Positive Integer = 100

Negative Integer = -100

2. Increment

The is used to increment the value of the variable by 1. The increment can be done in two
ways:

2.1 prefix increment

In this method, the operator precedes the operand (e.g., ++a). The value of the operand will
be altered before it is used.

Example:

2.2 postfix increment

In this method, the operator follows the operand (e.g., a++). The value operand will be
altered after it is used.

Example:

Below is the implementation of the increment ( ++ ):

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:

3.1 prefix decrement

In this method, the operator precedes the operand (e.g., – -a). The value of the operand will
be altered before it is used.

Example:

3.2 postfix decrement

In this method, the operator follows the operand (e.g., a- -). The value of the operand will be
altered after it is used.

Example:

Below is the implementation of the decrement ( — ):

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:

If x is true, then !x is false


If x is false, then !x is true

Below is the implementation of the NOT (!) operator:

10

if (!(a > b))

11

12
else

13

14

15

16

Output

a is greater than b

5. Addressof operator ( & )

The addressof operator ( & ) gives an address of a variable. It is used to return the memory
address of a variable. These addresses returned by the address-of operator are known as
pointers because they “point” to the variable in memory.

Example:

& gives an address on variable n


int a;
int *ptr;
ptr = &a; // address of a is copied to the location ptr.

Below is the implementation of the Addressof operator(&):

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.

Below is the implementation of sizeof() operator:

9
10

11

Output

Size of double: 8

Size of int: 4

Assignment Operators in C

Last Updated : 20 Mar, 2024

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.

Different types of assignment operators are shown below:

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:

If initially value stored in a is 5. Then (a += 6) = 11.


3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the
value on the right from the current value of the variable on left and then assigns the result
to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

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:

If initially value stored in a is 5. Then (a *= 6) = 30.

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:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

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

Last Updated : 29 Jul, 2024

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


Operators returns either 0 or 1, it depends on whether the expression result is true or false.
In C programming for decision-making, we use logical operators.

We have 3 logical operators in the C language:

Logical AND ( && )


Logical OR ( || )

Logical NOT ( ! )

Types of Logical Operators

1. Logical AND Operator ( && )

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

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

11

12

13

else {
14

15

16

17

Output

Both values are greater than 0

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

"greater than 0\n");

13

14

else {

15

16

17

18

Output

Any one of the given value is greater than 0

3. Logical NOT Operator ( ! )

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

!(operand_1 && operand_2)

Example

7
8

10

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

11

12

13

14

15

16

else {

17

18

19

20

Short Circuit Logical Operators

When the result can be determined by evaluating the preceding Logical expression without
evaluating the further operands, it is known as short-circuiting.

Short-circuiting can be seen in the equation having more than one Logical operator. They
can either AND, OR, or both.

1. Short Circuiting in Logical AND Operator

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

Example

1
2

using namespace std;

bool is_positive(int number)

if (number > 0)

10

else

11

12

13

14

bool is_even(int number)

15

16

if (number % 2 == 0)

17

18

else

19
20

21

22

23

24

25

26

27

28

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

29

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

30

31

else {

32

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

33

34

35

36

37
38

39

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

40

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

41

42

else {

43

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

44

45

46

47

Output

Both conditions are satisfied.

Conditions not satisfied.

2. Short Circuiting in Logical OR Operator

OR operator returns true if at least one operand evaluates to true. If the first operand is
true, then the further operands will not be evaluated. This is because even if the further
operands evaluate to false, the entire condition will still return true.

Example

2
3

using namespace std;

bool is_positive(int number)

if (number > 0)

10

11

else

12

13

14

15

16

bool is_even(int number)

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

cout << "At least one condition is satisfied."

33

<< endl;

34

35

else {

36

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

37

38
39

40

41

42

43

if (is_positive(y) || is_even(y)) {

44

cout << "At least one condition is satisfied."

45

<< endl;

46

47

else {

48

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

49

50

51

52

Output

At least one condition is satisfied.

Conditions not satisfied.

FAQs on Logical operators


Q1. What is the precedence of logical operators in programming?

Answer:

The precedence of logical operators is: NOT, AND, OR. However, it is always recommended
to use parentheses to make the order of evaluation explicit and avoid confusion.

Q2. Can logical operators be chained together?

Answer:

Yes, logical operators can be chained together to create complex conditions. For example,
we can combine multiple logical AND (&&) or logical OR (||) operators in a single expression
to evaluate multiple conditions simultaneously.

Q3. What will be the output of the following code?

void main()

Answer:

Q4. What will be the output of the following code?

4
5

if (i++ && (i == 1))

else

Answer:

Coding

Bitwise Operators in C

Last Updated : 10 Jan, 2025

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.

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

Example of Bitwise Operators in C

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

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

Time Complexity: O(1)


Auxiliary Space: O(1)

Interesting Facts About Bitwise Operators

1. The left-shift and right-shift operators should not be used for negative numbers.

If the second operand(which decides the number of shifts) is a negative number, it results in
undefined behavior in C. For example, results of both 1 <<- 1 and 1 >> -1 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 odd occurring element is 90

Time Complexity: O(n)


Auxiliary Space: O(1)

The following are many other interesting problems using the XOR operator.
.

4. The Bitwise operators should not be used in place of logical operators.

The result of logical operators (&&, || and !) is either 0 or 1, but bitwise operators return an
integer value. Also, the logical operators consider any non-zero operand as 1. For example,
consider the following program, the results of & & && are different for the same operands.

Example

The below program demonstrates the difference between & and && operators.

8
9

10

11

12

Output

False True

Time Complexity: O(1)


Auxiliary Space: O(1)

5. The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.

As mentioned in point 1, it works only if numbers are positive.

Example:

The below example demonstrates the use of left-shift and right-shift operators.

10

11
Output

x << 1 = 38

x >> 1 = 9

Time Complexity: O(1)


Auxiliary Space: O(1)

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

Time Complexity: O(1)


Auxiliary Space: O(1)

7. The ~ operator should be used carefully.


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

Example

The below example demonstrates the use of bitwise NOT operator.

unsigned int x = 1;

10

11

Try it on GfG Practice

Output

Signed Result -2
Unsigned Result 4294967294

Time Complexity: O(1)


Auxiliary Space: O(1)

Note The output of the above program is compiler dependent

Related Articles

Different ways to represent Signed Integer

Last Updated : 07 Jan, 2024

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 binary, signed Integer can be represented in three ways:

Let us see why 2’s complement is considered to be the best method.

Signed bit Representation

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

For 4 bit representation, minimum value=-7 and maximum value=+7

Signed bit Representation:

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

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’s Complement representation of a signed integer

In 1’s complement representation the following rules are used:

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.

1’s complement of 0 = 1 and 1’s complement of 1 = 0

Example:
(-5) in 1’s complement:
+5 = 0101
-5 = 1010

Write Unsigned representation of 2^n-1-X for –X.

Example: –X = -5 for n=4 2^4-1-5=10 ->1010(Unsigned)

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.

1’s Complement Representation:

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.

Merits over Signed bit representation:

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.

Example: Signed extension for +5

Signed extension for -5

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.

2’s Complement representation

In 2’s Complement representation the following rules are used:

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.

Write an unsigned representation of 2^n-X for –X in n-bit representation.

Example:
(-5) in 4-bit representation
2^4-5=11 -→1011(unsigned)

Write a representation of +X and take 2’s Complement.


To take 2’s complement simply take 1’s complement and add 1 to it.

Example:
(-5) in 2’s complement
(+5) = 0101
1’s complement of (+5) = 1010
Add 1 in 1010: 1010+1 = 1011
Therefore (-5) = 1011

3. Range of representation of n-bit is –(2^{n-1} ) to (2)^{(n-1)-1}.

2’s Complement representation (4 bits)

Merits:

No ambiguity in the representation of 0.

Numbers are in cyclic order i.e. after +7 comes -8.

Signed Extension works.

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 in C

Last Updated : 16 Dec, 2024

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.

Let’s take a look at an example:

1
2

res = a + b * c / 2;

10

11

12

13

Output

12

Explanation: The above expression is evaluated as 6 + ( (3 * 4) / 2) = 16, not (6 + 3) * (4 / 2)


= 18. So what guided the compiler to evaluate the expression in this way? It is actually the
precedence and associativity of the operators used in this expression.

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

Operator precedence determines which operation is performed first in an expression with


more than one operator with different precedence. Let’s try to evaluate the following
expression,
10 + 20 * 30

The expression contains two operators, + (addition) and * (multiplication). According to


operator precedence, multiplication (*) has higher precedence than addition (+), so
multiplication is checked first. After evaluating multiplication, the addition operator is then
evaluated to give the final result.

We can verify this using the following C program

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.

We can verify the above using the following C program:

Output

Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions.

Example of Operator Precedence and Associativity

In general, operator precedence and associativity are applied together in expressions.


Consider the expression exp = 100 + 200 / 10 – 3 * 10, where the division (/) and
multiplication (*) operators have the same precedence but are evaluated before addition (+)
and subtraction (-). Due to left-to-right associativity, the division is evaluated first, followed
by multiplication. After evaluating the division and multiplication, the addition and
subtraction are evaluated from left to right, giving the final result.
Again, we can verify this using the following C program.

10

11

Output

90

Operator Precedence and Associativity Table

The following tables list the C operator precedence from highest to lowest and the
associativity for each of the operators:

Easy Trick to Remember the Operators Associtivity and Precedence: PUMA’S REBL TAC

where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R = Relational, E =


Equality, B = Bitwise, L = Logical, T = Ternary, A = Assignment and C = Comma

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

You can check article for more details.

We can use parenthesis to change the order of evaluation

Parenthesis ( ) got the highest priority among all the C operators. So, if we want to change
the order of evaluation in an expression, we can enclose that particular operator in ( )
parenthesis along with its operands.

Example

Consider the given expression

100 + 200 / 10 – 3 * 10

= 90

But if we enclose 100 + 200 in parenthesis, then the result will be different.

=0

As the + operator will be evaluated before / operator.

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.

Precedence and associativity of postfix ++ and prefix ++ are different.

The precedence of postfix ++ is more than prefix ++, their associativity is also different. The
associativity of postfix ++ is left to right and the associativity of prefix ++ is right to left.
Check article for more details.
Comma has the least precedence among all operators and should be used carefully.

For example, consider the following program, the output is 1.

a = 1, 2, 3;

10

Output

There is no chaining of comparison operators in C

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

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.

You might also like