Introdction To C
Introdction To C
2. One of the key features of C++ is its ability to support low-level, system-level programming,
making it suitable for developing operating systems, device drivers, and other system
software. At the same time, C++ also provides a rich set of libraries and features for high-
level application programming, making it a popular choice for developing desktop
applications, video games, and other complex applications.
3. C++ has a large, active community of developers and users, and a wealth of resources and
tools available for learning and using the language. Some of the key features of C++ include:
5. Templates: C++ templates allow developers to write generic code that can work with any
data type, making it easier to write reusable and flexible code.
6. Standard Template Library (STL): The STL provides a wide range of containers and algorithms
for working with data, making it easier to write efficient and effective code.
7. Exception Handling: C++ provides robust exception handling capabilities, making it easier to
write code that can handle errors and unexpected situations.
Overall, C++ is a powerful and versatile programming language that is widely used for a range of
applications and is well-suited for both low-level system programming and high-level application
development. If you wish to learn C++ then you can enroll in our C++ Course provides a
comprehensive introduction to the C++ programming language, covering its fundamentals and best
practices.
Here are some simple C++ code examples to help you understand the language:
1.Hello World:
#include <iostream>
2
3
int main() {
return 0;
Output
Hello, World!
C++ is a middle-level language rendering it the advantage of programming low-level (drivers, kernels)
and even higher-level applications (games, GUI, desktop apps etc.). The basic syntax and code
structure of both C and C++ are the same.
Some of the features & key-points to note about the programming language are as follows:
Simple: It is a simple language in the sense that programs can be broken down into logical
units and parts, has a rich library support and a variety of data-types.
Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language,
and also hugely procedural. Newer languages have extra in-built default features such as
garbage-collection, dynamic typing etc. which slow the execution of the program overall.
Since there is no additional processing overhead like this in C++, it is blazing fast.
Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly
manipulate storage address. This helps in doing low-level programming (where one might
need to have explicit control on the storage of variables).
Object-Oriented: One of the strongest points of the language which sets it apart from C.
Object-Oriented support helps C++ to make maintainable and extensible programs. i.e.
Large-scale applications can be built. Procedural code becomes difficult to maintain as code-
size grows.
Here are some key points to keep in mind while working with C++:
2. Strong Type System: C++ has a strong type system, which means that variables have a
specific type and that type must be respected in all operations performed on that variable.
3. Low-level Access: C++ provides low-level access to system resources, which makes it a
suitable choice for system programming and writing efficient code.
4. Standard Template Library (STL): The STL provides a large set of pre-written algorithms and
data structures that can be used to simplify your code and make it more efficient.
5. Cross-platform Compatibility: C++ can be compiled and run on multiple platforms, including
Windows, MacOS, and Linux, making it a versatile language for developing cross-platform
applications.
6. Performance: C++ is a compiled language, which means that code is transformed into
machine code before it is executed. This can result in faster execution times and improved
performance compared to interpreted languages like Python.
7. Memory Management: C++ requires manual memory management, which can lead to errors
if not done correctly. However, this also provides more control over the program’s memory
usage and can result in more efficient memory usage.
8. Syntax: C++ has a complex syntax that can be difficult to learn, especially for beginners.
However, with practice and experience, it becomes easier to understand and work with.
These are some of the key points to keep in mind when working with C++. By understanding these
concepts, you can make informed decisions and write effective code in this language.
Applications of C++:
C++ finds varied usage in applications such as:
Cloud/Distributed Systems
Advantages of C++:
1. Performance: C++ is a compiled language, which means that its code is compiled into
machine-readable code, making it one of the fastest programming languages.
3. Standard Template Library (STL): The STL provides a wide range of algorithms and data
structures for working with data, making it easier to write efficient and effective code.
4. Machine Independent: C++ is not tied to any hardware or processor. If the compiler compiles
the program in the system, it will be able to run no matter what the hardware is.
5. Large Community: C++ has a large, active community of developers and users, providing a
wealth of resources and support for learning and using the language.
Disadvantages of C++:
1. Steep Learning Curve: C++ can be challenging to learn, especially for beginners, due to its
complexity and the number of concepts that need to be understood.
2. Verbose Syntax: C++ has a verbose syntax, which can make code longer and more difficult to
read and maintain.
3. Error-Prone: C++ provides low-level access to system resources, which can lead to subtle
errors that are difficult to detect and fix.
Here are some awesome facts about C++ that may interest you:
1. The name of C++ signifies the evolutionary nature of the changes from C. “++” is the C
increment operator.
2. C++ is one of the predominant languages for the development of all kind of technical and
commercial software.
3. C++ introduces Object-Oriented Programming, not present in C. Like other things, C++
supports the four primary features of OOP: encapsulation, polymorphism, abstraction, and
inheritance.
5. A function is a minimum requirement for a C++ program to run.(at least main() function)
Reference Books:
2. “Effective C++: 55 Specific Ways to Improve Your Programs and Designs” by Scott Meyers
Object-Oriented Programming
Machine Independent
Simple
High-Level Language
Popular
Case-sensitive
Compiler Based
Memory Management
Multi-threading
1. Object-Oriented Programming
Class
Objects
Encapsulation
Polymorphism
Inheritance
Abstraction
2. Machine Independent
A C++ executable is not platform-independent (compiled programs on Linux won’t run on Windows),
however, they are machine-independent. Let us understand this feature of C++ with the help of an
example. Suppose you have written a piece of code that can run on Linux/Windows/Mac OSx which
makes the C++ Machine Independent but the executable file of the C++ cannot run on different
operating systems.
3. Simple
It is a simple language in the sense that programs can be broken down into logical units and parts,
has rich library support and has a variety of data types. Also, the Auto Keyword of C++ makes life
easier.
Auto Keyword
The idea of the auto keyword was to form the C++ compiler to deduce the data type while compiling
instead of making you declare the data type every freaking time. Do keep in mind that you cannot
declare something without an initializer. There must be some way for the compiler to deduce your
type.
Example:
C++
#include <bits/stdc++.h>
int main()
// Variables
// Print typeid
return 0;
Output:
4. High-Level Language
C++ is a High-Level Language, unlike C which is a Mid-Level Programming Language. It makes life
easier to work in C++ as it is a high-level language it is closely associated with the human-
comprehensible English language.
5. Popular
C++ can be the base language for many other programming languages that supports the feature of
object-oriented programming. Bjarne Stroustrup found Simula 67, the first object-oriented language
ever, lacking simulations, and decided to develop C++.
6. Case-sensitive
It is clear that C++ is a case-sensitive programming language. For example, cin is used to take input
from the input stream. But if the “Cin” won’t work. Other languages like HTML and MySQL are not
case-sensitive languages.
7. Compiler Based
C++ is a compiler-based language, unlike Python. That is C++ programs used to be compiled and their
executable file is used to run them. C++ is a relatively faster language than Java and Python.
When the program executes in C++ then the variables are allocated the dynamical heap space. Inside
the functions, the variables are allocated in the stack space. Many times, We are not aware in
advance how much memory is needed to store particular information in a defined variable and the
size of required memory can be determined at run time.
9. Memory Management
C++ allows us to allocate the memory of a variable or an array in run time. This is known
as Dynamic Memory Allocation.
In other programming languages such as Java and Python, the compiler automatically
manages the memories allocated to variables. But this is not the case in C++.
In C++, the memory must be de-allocated dynamically allocated memory manually after it is
of no use.
The allocation and deallocation of the memory can be done using the new and delete
operators respectively.
Example:
C++
#include <cstring>
#include <iostream>
// Driver Code
int main()
int num = 5;
float* ptr;
// Memory allocation of
*(ptr + i) = i;
<< endl;
delete[] ptr;
return 0;
Output:
Student1: 0
Student2: 1
Student3: 2
Student4: 3
Student5: 4
10. Multi-threading
Multithreading is a specialized form of multitasking and multitasking is a feature that allows
your system to execute two or more programs concurrently. In general, there are two sorts
of multitasking: process-based and thread-based.
A multithreaded program contains two or more parts that will run concurrently. Each part of
such a program is named a thread, and every thread defines a separate path of execution.
C++ doesn’t contain any built-in support for multithreaded applications. Instead, it relies
entirely upon the OS to supply this feature.
Example:
C++
#include <cstdlib>
#include <iostream>
#include <pthread.h>
#define NUM_THREADS 5
// the thread id
// Thread ID
long tid;
tid = (long)threadid;
pthread_exit(NULL);
// Driver Code
int main()
// Create thread
pthread_t threads[NUM_THREADS];
int rc;
int i;
rc = pthread_create(&threads[i],
NULL,
PrintHello,
(void*)&i);
if (rc) {
pthread_exit(NULL);
Output:
This tutorial assumes that you are working on Linux OS and we are going to write a multi-threaded
C++ program using POSIX. POSIX Threads or Pthreads provide API which is available on many Unix-
like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X, and Solaris.
History of C++
The C++ language is an object-oriented programming language & is a combination of both low-level
& high-level language – a Middle-Level Language. The programming language was created, designed
& developed by a Danish Computer Scientist – Bjarne Stroustrup at Bell Telephone Laboratories (now
known as Nokia Bell Labs) in Murray Hill, New Jersey. As he wanted a flexible & a dynamic language
which was similar to C with all its features, but with additionality of active type checking, basic
inheritance, default functioning argument, classes, inlining, etc. and hence C with Classes (C++) was
launched.
C++ was initially known as “C with classes, ” and was renamed C++ in 1983. ++ is shorthand for
adding one to variety in programming; therefore C++ roughly means that “one higher than C.”
The trace of the programming language C++ can be done back to 1979 when Bjarne
Stroustrup was doing some development for this thesis for PhD. One in all the words
Stroustrup had the chance to figure with, was a language referred to as Simula, that because
the name implies, could be a language primarily designed for simulations. The Simula sixty-
seven language – that was the variant that Stroustrup worked with is considered the primary
language to support the object-oriented programming paradigm. Stroustrup found that this
paradigm was helpful for package development; but, the Simula language was way too slow
for practice & practical use.
Shortly subsequently, he began work on “C with Classes“, because what the name implies
was meant to be a superset of the C language. His main dream was to get his advanced
object-oriented programming, created by him, into the C language, which was during his era
was still the programming language that was widely respected for its movability, portability &
compactness, by not sacrificing the speed or the low-level practicality. His programming
language enclosed inlining, basic inheritance, default function arguments, categories, and
reliable sort was checking additionally to all or any the options of the C language.
The first C with categories compiler was referred to as Cfront, that got derived from a C
compiler referred to as CPre. It had been a program designed to translate C with categories
code to universal C. A rather attention-grabbing purpose value noting is that Cfront was
written mostly in C with classes, creating it a self-hosting compiler (a compiler which will
compile itself). Cfront would later be abandoned in 1993 when it became troublesome to
integrate new options into it, mainly C++ exceptions. Even so, Cfront created a significant
impact on the implementations of future compilers and also the operating system UNIX.
In 1983, the name of the language got modified from C with categories to C++. The ++
operator within the C language is the associate operator for incrementing a variable, which
provides some insight into however Stroustrup regarded the programming language. Several
new options got additional around this point, the foremost notable of that area unit virtual
functions, perform overloading, references with the const keyword, and single-line
comments by using the two forward slashes (which may be a feature taken from the
language BCPL).
In 1985, Stroustrup’s relation to the language entitled The C++ programming language was
printed and got released. That very same year, C++ got enforced as an advertisement
product and hence starting of it as a commercial element. The programming language wasn’t
formally standardized, nevertheless creating the book an essential reference. The
programming language was updated once more in 1989 to incorporate protected and static
members, still as an associate inheritance from many categories & classes.
In 1990, The Annotated C++ manual, which was a reference got released all over. In 1990
only, in the same & identical year, Borland’s Turbo C++ compiler would also be commercially
discharged as an advertisement product. Turbo C++ additional an excessiveness of other
libraries which might have a substantial impact on C++’s development. Though Turbo C++’s
last stable unharness was in 2006, the compiler continues to get widely used.
In 1998, the C++ customary advisory & standards committee printed the first international
standard for C++ ISO/IEC 14882:1998, which might be informally called C++98. The
Annotated C++ manual was aforementioned to be a significant influence within the
development of the quality. The quality template library (also known as the Standard
Template Library) that began its intellectual construction in 1979 got additionally enclosed in
it. In 2003, the committee well-versed multiple issues that were according with their 1998
customary and revised it consequently. The modified language got dubbed as C++03.
In 2005, the same committee of C++ discharged a technical report (called as TR1)
particularization varied options they were aiming to boost the newest C++ standard. The new
rule was informally dubbed C++0x because it was expected to be discharged someday before
the tip of the first decade. Ironically, however, the new customary wasn’t fulfilled until mid-
2011. Many technical reports were discharged up till then, and a few compilers began adding
experimental support for the new options and features.
In mid-2011, the new C++ customary (dubbed C++11) got finished. The Boost library project
created a substantial impact on the new rule, and a few of the new modules were derived
directly from the corresponding Boost libraries. A number of the new options that got
included were:
1. New for loop syntax providing practicality just like foreach loops in specific different
languages
2. Customary threading library (which up till 2011 each C and C++ were lacking)
3. Variadic templates
C++20 is the latest version of C++. A newer & advanced version of C++ is being released, i.e.
C++23.
C++ is still the third most popular programming language according to the TIOBE Index’s
latest study of 2019, behind Java & C, by knocking out Python. All credits for this go to the
newly released C++11 version, which according to the users made it much robust, safer,
easier simpler, and more expressive.
Bjarne Stroustrup has created excellent work with C++. C could be a low-level programming
language, and so, it does not have any classes. It does not contain several options which will create
programming more well-off, however, is that the quickest language (assembly is more rapid;
however, programming in construction isn’t one thing you’d consider), what Bjarne Stroustrup did he
additional the thing orientated half, by treating code like life objects. What makes C++ therefore
lovely is that it’s the speed of C and it’s additionally a high-level programming language, therefore
allow us to say the most effective of each world. However on the opposite hand, C++ is challenging
to be noted to newbies, and for an equivalent code that you wrote on C++, you’ll be able to write in
Python for the quarter of the time.
Features of C++:
The five best features of C++ are:-
1. It is the most primarily used language in competitive programming as far as facts go. Most of
the extremely rated coders typically use C++ for cryptography. You’ll see it on any online
websites.
2. STL (standard guide library): Its an extremely time-saver for people who recognize C and still
writing code for bubble type.
3. Operator overloading
Release
Version Date Major changes
14882:1998) 1998
Future
C++23 The next major revision of the C++ standard
Release
1. The name of C++ signifies the evolutionary nature of the changes from C. “++” is the C
increment operator.
2. C++ is one of the predominant languages for the development of all kinds of technical and
commercial software.
3. C++ introduces Object-Oriented Programming, not present in C. Like other things, C++
supports the four primary features of OOP: encapsulation, polymorphism, abstraction, and
inheritance.
6. C and C++ have invented in the same place i.e. at AT&T (American Telephone & Telegraph)
bell laboratories, located in the U.S.A.
7. Not purely object-oriented: We can write C++ code without using classes and it will compile
without showing any error message. The language has some extensions over C, that make
OOP and generic programming more convenient.
8. Many programming languages are influenced by c++, some of which include C#, Java, and
even newer versions of C.
10. A major reason behind the success of C++ is that it supports various programming styles.
11. It is a multiparadigm programming language that not only supports the OOP paradigm but
also many other paradigms.
C++ is often viewed as a superset of C. C++ is also known as a “C with class” This was very nearly true
when C++ was originally created, but the two languages have evolved over time with C picking up a
number of features that either weren’t found in the contemporary version of C++ or still haven’t
made it into any version of C++. That said, C++ is still mostly a superset of C adding Object-Oriented
Programming, Exception Handling, Templating, and a more extensive standard library.
Below is a table of some of the more obvious and general differences between C and C++. There are
many more subtle differences between the languages and between versions of the languages.
Aspect C C++
C++
C does not support polymorphism,
supports polymorphism, encapsulatio
encapsulation, and inheritance which
n, and inheritance because it is an
means that C does not support
object-oriented programming
object-oriented programming.
OOPs Support language.
Subset/
C is (mostly) a subset of C++. C++ is (mostly) a superset of C.
Superset
Encapsulation Data and functions are separated in C Data and functions are encapsulated
because it is a procedural
Aspect C C++
Function Inside Functions in C are not defined inside Functions can be used inside a
Structures structures. structure in C++.
Virtual Virtual and friend functions are not Virtual and friend functions are
Functions supported by C. supported by C++.
Named Named initializers may appear out of Named initializers must match the
Initializers order data layout of the struct
The “Hello World” program is the first step towards learning any programming language and is also
one of the most straightforward programs you will learn. It is the basic program that is used to
demonstrate how the coding process works. All you have to do is display the message “Hello World”
on the output screen.
Below is the C++ program to print “Hello World” on the console screen.
#include <iostream>
int main() {
10
11
12
return 0;
13
}
Try it on GfG Practice
Output
Hello World
To write and run C++ programs, you need to set up the local environment on your computer. Refer to
the complete article Setting up C++ Development Environment. If you do not want to set up the local
environment on your computer, you can also use online IDE to write and run your C++ programs.
Let us now understand every line and the terminologies of the above program.
This line is a comment line. A comment is used to display additional information about the program.
A comment does not contain any programming logic. When a comment is encountered by a
compiler, the compiler simply skips that line of code.
#include <iostream>
The #include is a preprocessor directive tells the compiler to include the content of a file in the
source code. For example, #include<iostream> tells the compiler to include the input-output library
which contains all C++’s input/output library functions.
This is used to import the entity of the stdnamespace into the current namespace of the program. It
is basically the space where all the inbuilt features of C++ are declared. For example, std::cout.
int main() { }
The main() function is the entry point of every C++ program, no matter where the function is located
in the program. The opening braces ‘{‘ indicates the beginning of the main function and the closing
braces ‘}’ indicates the ending of the main function.
cout<<“Hello World”;
The coutis a tool (object) that is used to display output on the console screen. Everything followed by
the character << in double quotes ” ” is displayed on the output screen. The semi-colon character at
the end of the statement is used to indicate that the statement is ending there.
return 0
This statement is used to return a value from a function and indicates the finishing of a function.
Here, it is used to sent the signal of successful execution of the main function.
Also, as you can see, the cout and the return statement have been indented or moved to the right
side. This is done to make the code more readable. We must always use indentations and comments
to make the code more readable. Must read the FAQ on the style of writing programs.
C++ Variables
In C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The
value stored in a variable can be accessed or changed during program execution. In this article, we
will learn about the variables in C++ and how to use them in our programs.
#include <iostream>
int main() {
int var;
10
var = 100;
12
13
14
15
16
return 0;
17
Output
100
Explanation: A variable with name var is created. It is of the type int (keyword for integer) and can
store the whole numbers. In the next step, we assigned a value 100 to it and finally, we access the
stored value using the variable’s name.
The C++ Course covers the types of variables in C++ and how to use them effectively in your
programs.
Syntax of Variables
Creating a variable and giving it a name is called variable definition. The syntax of variable definition
is:
type name;
Here,
Types of Variables
The names given to a variable is called identifiers. There are some rules for giving a name to the
variable:
The name of the variable is case sensitive (e.g. Arr and arr both are different variables).
The name of the variable does not contain any whitespace and special characters (ex #, $, %,
*, etc).
All the variable names must begin with a letter of the alphabet or an underscore (_).
We cannot used C++ keyword (e.g. float, double, class) as a variable name.
Variable Initialization
The next step is initialization. It means assigning an initial value to the variable. It is done by using
an assignment operator = with the variable name as left operand and the value as the right operand.
The value should be of the same type as variable. For example, a variable declared as int var; should
only store the integer variable.
Examples of Variables
The below examples demonstrate how to use the variables in our C++ programs:
#include <iostream>
3
4
int main() {
// Defining a variable
10
int age2;
11
12
13
age2 = 99;
14
15
// Displaying variable
16
17
18
return 0;
19
}
Output
15
99
#include <iostream>
int main() {
10
c = 'c';
11
12
cout << a << " " << b << " " << c;
13
return 0;
14
Output
ABc
When a variable is declared, the compiler is told about the variable name and the type of data it will
store. It is not allocated the any memory at this point. It is when the variable is defined it is allocated
the memory. The amount of memory allocated depends upon the type of data that a variable intends
to store.
Initially, the variable only stores some garbage value (value that does not mean anything). At the
time of initialization, it is assigned some meaningful value that using the assignment operator that is
then stored in the memory allocated to the function. So basically, we are manipulating a specific part
of memory using the variable name.
At last, the data stored in the allocated memory can be accessed using the variable name.
Note: All the above syntax of creating a variable is variable definition as compiler automatically. To
only declare a variable in C++, we can use the extern keyword. Refer to this article to learn more –
Difference between Definition and Declaration
Constants in C
The constants in C are the read-only variables whose values cannot be modified once they are
declared in the C program. The type of constant can be an integer constant, a floating pointer
constant, a string constant, or a character constant. In C language, the const keyword is used to
define the constants.
In this article, we will discuss about the constants in C programming, ways to define constants in C,
types of constants in C, their properties and the difference between literals and constants.
What is a constant in C?
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.
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.
Example of Constants in C
#include <stdio.h>
int main()
5
{
10
11
12
13
14
15
16
17
int_const);
18
19
char_const);
20
float_const);
22
23
return 0;
24
Output
One thing to note here is that we have to initialize the constant variables at declaration. Otherwise,
the variable will store some garbage value and we won’t be able to change it. The following image
describes examples of incorrect and correct variable definitions.
Types of Constants in C
The type of the constant is the same as the data type of the variables. Following is the list of the
types of constants
Integer Constant
Character Constant
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:
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.
// variable
#include <stdio.h>
int main()
10
var = 20;
11
12
13
return 0;
14
Output
In function 'main':
10:9: error: assignment of read-only variable 'var'
10 | var = 20;
| ^
The constant and literals are often confused as the same. But in C language, they are different
entities and have different semantics. The following table lists the differences between the constants
and literals in C:
Constant Literals
Constants are variables that cannot be Literals are the fixed values that define
modified once declared. themselves.
We can also define a constant in C using #define preprocessor. 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.
#include <stdio.h>
#define pi 3.14
int main()
return 0;
10
Output
Note: This method for defining constant is not preferred as it may introduce bugs and make the code
difficult to maintain.
FAQs on C Constants
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.
Answer:
The const keyword is the qualifier that is used to declare the constant variable in C language.
Answer:
Answer:
The right way to declare a constant in C is to always initialize the constant variable when we declare.
Q5. What is the difference between constant defined using const qualifier and #define?
Answer:
The following table list the differences between the constants defined using const qualifier and
#define in C:
They are handled by the compiler. They are handled by the preprocessor.
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.
2
#include <stdio.h>
int main()
10
11
12
int* ptr
13
14
// changing value
15
*ptr = 500;
16
17
19
return 0;
20
Output
Const Qualifier in C
The qualifier const can be applied to the declaration of any variable to specify that its value will not
be changed (which depends upon where const variables are stored, we may change the value of the
const variable by using a pointer). The result is implementation-defined if an attempt is made to
change a const.
Using the const qualifier in C is a good practice when we want to ensure that some values should
remain constant and should not be accidentally modified. Let’s take a look at an example:
#include <stdio.h>
int main() {
const a = 10;
printf("%d", a);
10
a = 11;
11
12
return 0;
13
Output
6| const a = 10;
| ^
10 | a = 11;
| ^
Explanation: In the above program, we created a constant variable whose value is not expected to be
changed thoughout the whole program. But when we try to change the value, the compiler throws
an error.
In C programming, apart from defining a constant variable, the const qualifier can be used in
different contexts to provide various behaviours. Here are some different use cases of
the const qualifier in C:
Table of Content
Pointer to Constant
Constant Pointer to Variable
To understand how constants can enhance data structures and program safety, the C Programming
Course Online with Data Structures covers constants in-depth, along with their practical
applications.
Pointer to Constant
Pointer to a constant means that the value that the pointer is pointing to is constant.
We can change the pointer to point to any other integer variable but cannot change the value of the
object (entity) pointed using pointer. The pointer is stored in the read-write area (stack in the present
case). The object pointed may be in the read-only or read-write area.
Example 1:
#include <stdio.h>
int main() {
int i = 10;
int j = 20;
*ptr = 100;
ptr = &j;
printf("ptr: %d\n", *ptr);
return 0;
Output
*ptr = 100;
#include <stdio.h>
int main() {
int j = 20;
*ptr = 100;
ptr = &j;
Output
*ptr = 100;
Down qualification may cause warnings in C. It refers to the situation where a qualified type is
assigned to a non-qualified type.
#include <stdio.h>
int main() {
int i = 10;
10
11
12
13
14
ptr = &j;
15
16
17
18
return 0;
19
Output
main.c:16:9: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-
qualifiers]
16 | ptr = &j;
| ^
*ptr: 10
*ptr: 20
Constant pointer means that the pointer itself is a constant. It means that we cannot change the
pointer to point to another variable.
// to another variable
#include <stdio.h>
int main(void)
int i = 10;
int j = 20;
return 0;
Output
This type of pointer is a constant pointer to a constant variable which means we cannot change the
value pointed by the pointer as well as we cannot point the pointer to other variables.
#include <stdio.h>
int main(void)
int i = 10;
int j = 20;
return 0;
Output
Enhanced Type Safety: By using const, you can ensure that values are not accidentally
modified, reducing the chance of bugs and errors in your code.
Improved Optimization: Compilers can optimize const variables more effectively, as they
know that their values will not change during program execution. This can result in faster and
more efficient code.
Better Memory Usage: By declaring variables as const, you can often avoid having to make a
copy of their values, which can reduce memory usage and improve performance.
Improved Compatibility: By declaring variables as const, you can make your code more
compatible with other libraries and APIs that use const variables.
Improved Reliability: By using const, you can make your code more reliable, as you can
ensure that values are not modified unexpectedly, reducing the risk of bugs and errors in
your code.
Summary
Constant Pointer to
int * const ptr Yes No
Variable
There are many different ways to make the variable as constant in C. Some of the popular ones are:
2. Using Macros
The const keyword specifies that a variable or object value is constant and can’t be modified at the
compilation time.
Syntax
Example
#include <stdio.h>
int main()
return 0;
2. Using Macros
We can also use Macros to define constant, but there is a catch. Since Macros are handled by the
pre-processor(the pre-processor does text replacement in our source file, replacing all occurrences
of ‘var’ with the literal 5) not by the compiler. Hence it wouldn’t be recommended because Macros
doesn’t carry type checking information and also prone to error. In fact not quite constant as ‘var’
can be redefined like this.
Syntax
Example
// in 'Macros'
#include <stdio.h>
#define var 5
int main()
10
#ifdef var
11
#undef var
12
13
// redefine var as 10
14
#define var 10
15
#endif
16
17
printf("%d", var);
18
return 0;
19
Output
5 10
Note: preprocessor and enum only works as a literal constant and integers constant respectively.
Hence they only define the symbolic name of constant. Therefore if you need a constant variable with
a specific memory address use either ‘const’ or ‘constexpr’ according to the requirement.
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral
constants, that make a program easy to read and maintain.
Example
// constant
#include <stdio.h>
10
11
12
int main()
13
14
15
16
return 0;
17
Output
Note: The data types of enum are of course limited as we can see in above example.