0% found this document useful (0 votes)
28 views49 pages

Introdction To C

Uploaded by

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

Introdction To C

Uploaded by

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

ction to C++ Programming Language

Last Updated : 11 Oct, 2024

C++ is a general-purpose programming language that was developed as an enhancement of the C


language to include object-oriented paradigm. It is an imperative and a compiled language.

1. C++ is a high-level, general-purpose programming language designed for system and


application programming. It was developed by Bjarne Stroustrup at Bell Labs in 1983 as an
extension of the C programming language. C++ is an object-oriented, multi-paradigm
language that supports procedural, functional, and generic programming styles.

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:

4. Object-Oriented Programming: C++ supports object-oriented programming, allowing


developers to create classes and objects and to define methods and properties for these
objects.

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

std::cout << "Hello, World!" << std::endl;

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.

 Machine Independent but Platform Dependent: A C++ executable is not platform-


independent (compiled programs on Linux won’t run on Windows), however they are
machine independent.

 Mid-level language: It is a mid-level language as we can do both systems-programming


(drivers, kernels, networking etc.) and build large-scale user applications (Media Players,
Photoshop, Game Engines etc.)
 Rich library support: Has a rich library support (Both standard ~ built-in data structures,
algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid
development.

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

 Compiled Language: C++ is a compiled language, contributing to its speed.

Here are some key points to keep in mind while working with C++:

1. Object-Oriented Programming: C++ is an object-oriented programming language, which


means that it allows you to define classes and objects to model real-world entities and their
behavior.

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:

 Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)

 Browsers (Chrome & Firefox)

 Graphics & Game engines (Photoshop, Blender, Unreal-Engine)

 Database Engines (MySQL, MongoDB, Redis etc.)

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

2. Object-Oriented Programming: C++ supports object-oriented programming, which makes it


easier to write and maintain large, complex applications.

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.

Some interesting facts about C++:

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.

4. C++ got the OOP features from Simula67 Programming language.

5. A function is a minimum requirement for a C++ program to run.(at least main() function)
Reference Books:

1. “The C++ Programming Language” by Bjarne Stroustrup

2. “Effective C++: 55 Specific Ways to Improve Your Programs and Designs” by Scott Meyers

3. “C++ Primer Plus” by Stephen Prata

4. “C++ For Dummies” by Stephen R. Davis

5. “Data Structures and Algorithm Analysis in C++” by Mark Allen Weiss

C++ is a general-purpose programming language that was developed as an enhancement of the C


language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has
a number of features, including:

 Object-Oriented Programming

 Machine Independent

 Simple

 High-Level Language

 Popular

 Case-sensitive

 Compiler Based

 Dynamic Memory Allocation

 Memory Management

 Multi-threading
1. Object-Oriented Programming

C++ is an Object-Oriented Programming Language, unlike C which is a procedural programming


language. This is the most important feature of C++. It can create/destroy objects while
programming. Also, It can create blueprints with which objects can be created. We have discussed
the Object-Orient Programming Concepts in C++ in this article.

Concepts of Object-oriented programming Language:

 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++

// C++ program to demonstrate

// working of auto keyword

#include <bits/stdc++.h>

using namespace std;


// Driver Code

int main()

// Variables

auto an_int = 26;

auto a_bool = false;

auto a_float = 26.24;

auto ptr = &a_float;

// Print typeid

cout << typeid(a_bool).name() << "\n";

cout << typeid(an_int).name() << "\n";

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.

8. Dynamic Memory Allocation

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

// C++ Program to implement

// the Memory Management

#include <cstring>

#include <iostream>

using namespace std;

// Driver Code

int main()

int num = 5;

float* ptr;
// Memory allocation of

// num number of floats

ptr = new float[num];

for (int i = 0; i < num; ++i) {

*(ptr + i) = i;

cout << "Display the GPA of students:" << endl;

for (int i = 0; i < num; ++i) {

cout << "Student" << i + 1 << ": " << *(ptr + i)

<< endl;

// Ptr memory is released

delete[] ptr;

return 0;

Output:

Display the GPA of students:

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.

 Process-based multitasking handles the concurrent execution of programs. Thread-based


multitasking deals with the multiprogramming of pieces of an equivalent program.

 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++

// C++ Program to implement

// the working of Multi-threading

#include <cstdlib>

#include <iostream>

#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

// Function to print Hello with

// the thread id

void* PrintHello(void* threadid)

// Thread ID

long tid;

tid = (long)threadid;

// Print the thread ID


cout << "Hello World! Thread ID, "

<< tid << endl;

pthread_exit(NULL);

// Driver Code

int main()

// Create thread

pthread_t threads[NUM_THREADS];

int rc;

int i;

for (i = 0; i < NUM_THREADS; i++) {

cout << "main() : creating thread, "

<< i << endl;

rc = pthread_create(&threads[i],

NULL,

PrintHello,

(void*)&i);

// If thread is not created

if (rc) {

cout << "Error:unable to"

<< " create thread, "

<< rc << endl;


exit(-1);

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

Last Updated : 13 Jun, 2022

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

4. Automotive vehicle (AUTO) keyword


5. New instrumentation categories & classes

6. New C++ time library, atomics support

7. Comprehensive organization library

8. Regular expression support

9. Higher support for unions and array-initialization lists

 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

4. Multiple inheritances. Voluminous languages don’t have this facility.

5. Ability to modularize code, encapsulation, and polymorphism after all.

Summary Table of history of various C++ versions:

Release
Version Date Major changes

C++98 (ISO/IEC October The first version


Release
Version Date Major changes

14882:1998) 1998

C++03 (ISO/IEC February


Introduction of value initialization.
14882:2003) 2003

Introduction of Lambda Expressions, Delegating


August
C++11 Constructors, Uniform Initialization Syntax, nullptr, Automatic
2011
Type Deduction and decltype, Rvalue References etc.

Introduction of polymorphic lambdas, digit separators,


August
C++14 generalized lambda capture, variable templates, binary
2014
integer literals, quoted strings etc.

Introduction of fold expressions, hexadecimal floating point


December
C++17 literals, a u8 character literal, selection statements with
2017
initializer, inline variables etc.

March This update extends C++ with the facilities to inspect


C++20 program entities such as variables, enumerations, classes
2020 and their members, lambdas and their captures, etc.

Future
C++23 The next major revision of the C++ standard
Release

teresting Facts about C++

Last Updated : 02 Jun, 2022

C++ is a general-purpose, object-oriented programming language. It supports generic programming


and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-
Classes, and in 1983 with the C++.
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 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.

4. C++ got the OOP features from Simula67 Programming language.

5. A function is a minimum requirement for a C++ program to run.

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.

9. Concept of reference variables: operator overloading borrowed from Algol 68 programming


language.

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.

Difference between C and C++

Last Updated : 11 Jan, 2025

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 was developed by Dennis Ritchie


C++ was developed by Bjarne
between the year 1969 and 1973 at
Stroustrup in 1979.
Developer AT&T Bell Labs.

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

Number of keywords in C: Number of keywords in C++:


– C90: 32 – C++98: 63
– C99: 37 – C++11: 73
– C11: 44 – C++17: 73
Keywords – C23: 59 – C++20: 81

C++ is known as hybrid language


For the development of code, C because C++ supports both
Programming supports procedural programming. procedural and object-oriented
Paradigm programming paradigms.

Encapsulation Data and functions are separated in C Data and functions are encapsulated
because it is a procedural
Aspect C C++

programming language. together in form of an object in C++.

Data is hidden by the Encapsulation to


C does not support data hiding. ensure that data structures and
Data Hiding operators are used as intended.

C is a function driven language C++ is an object driven language


Focus of because C is a procedural because it is an object-oriented
Language programming language. programming.

Function and operator overloading is Function and operator overloading is


Overloading not supported in C. supported by C++.

Function Inside Functions in C are not defined inside Functions can be used inside a
Structures structures. structure in C++.

Namespace features are not present Namespace is used by C++, which


Namespaces inside the C. avoid name collisions.

Standard IO header is stdio.h and Standard IO header is iostream.h and


uses scanf() and printf() functions are uses cin and cout are used for
Standard I/O used for input/output in C. input/output in C++.

Reference variables are not Reference variables are supported by


References supported by C. C++.

Virtual Virtual and friend functions are not Virtual and friend functions are
Functions supported by C. supported by C++.

Inheritance C does not support inheritance. C++ supports inheritance.

Dynamic C C++ provides new operator for


Memory provides malloc() and calloc() functio memory allocation and delete
Aspect C C++

ns for dynamic memory allocation,


operator for memory de-allocation.
and free() for memory de-allocation.

Exception Direct support for exception handling Exception handling is supported by C+


Handling is not supported by C. +.

Access C structures don’t have access


C ++ structures have access modifiers.
Modifiers modifiers.

Strict type checking in done in C++.


There is no strict type checking in C So many programs that run well in C
programming language. compiler will result in many warnings
Type Checking and errors under C++ compiler.

Type punning with unions is


Type punning with unions is allows
Type Punning undefined behavior (except in very
(C99 and later)
with Unions specific circumstances)

Named Named initializers may appear out of Named initializers must match the
Initializers order data layout of the struct

File extension is “.cpp” or “.c++” or


File extension is “.c”
Extension “.cc” or “.cxx”

Meta-programming using templates


Meta-programming using macros and
Generic (macros are still supported but
_Generic()
Programming discouraged)

Writing First C++ Program – Hello World Example

Last Updated : 11 Jan, 2025


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.

C++ Hello World Program

Below is the C++ program to print “Hello World” on the console screen.

// Header file for input output functions

#include <iostream>

using namespace std;

// main() function: where the execution of

// C++ program begins

int main() {

// This statement prints "Hello World"

10

cout << "Hello World";

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.

Working of Hello World Program in C++

Let us now understand every line and the terminologies of the above program.

// C++ program to display “Hello World”

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.

using namespace std

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

Last Updated : 19 Dec, 2024

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.

Let’s take a look at an example:

#include <iostream>

using namespace std;

int main() {

// A variable that may store the data of

// int type (whole numbers)

int var;

10

// Assigning a whole number


11

var = 100;

12

13

// Printing the variable

14

cout << var;

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,

 type: type of data that a variable can store.

 name: name assigned to the variable.

Multiple variables of the same type can be defined as:

type name1, name2, name3 ….;

Types of Variables

In C++, following are the data types a variable can store:


 int: For storing integers or whole numbers.

 float: For storing real numbers with decimal points.

 char: For storing single characters.

 bool: For storing boolean value i.e. true and false.

 string: For storing the textual data.

Rules For Naming Variable

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 contains letters, digits, and underscores.

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

Some valid variable names: x, var, _here, arr40


Some invalid variable names: 89, a b, double

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.

type name = value; // At the time of declaration


name = value; // After declaration
type name1 = value1, name2 = value2; // For multiple variables

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:

Store Data in a Variable and Print It

#include <iostream>

using namespace std;

3
4

int main() {

// Defining and initializing a variable

int age1 = 15;

// Defining a variable

10

int age2;

11

12

// Initialize the variable

13

age2 = 99;

14

15

// Displaying variable

16

cout << age1 << endl;

17

cout << age2;

18

return 0;

19
}

Output

15

99

Create Multiple Variables at Once

#include <iostream>

using namespace std;

int main() {

// Creating three variables that store characters

char a = 'A', b = 'B', c = 'C';

// Update the value

10

c = 'c';

11

12

cout << a << " " << b << " " << c;

13
return 0;

14

Output

ABc

Memory Management of Variables

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

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

// C program to illustrate constant variable definition

#include <stdio.h>

int main()

5
{

// defining integer constant using const keyword

const int int_const = 25;

10

// defining character constant using const keyword

11

const char char_const = 'A';

12

13

// defining float constant using const keyword

14

const float float_const = 15.66;

15

16

printf("Printing value of Integer Constant: %d\n",

17

int_const);

18

printf("Printing value of Character Constant: %c\n",

19

char_const);

20

printf("Printing value of Float Constant: %f",


21

float_const);

22

23

return 0;

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.

// C Program to demonstrate the behaviour of constant

// variable

#include <stdio.h>

int main()

// declaring a constant variable

const int var;

// initializing constant variable var after declaration

10
var = 20;

11

12

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

13

return 0;

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:

Constant Literals

Constants are variables that cannot be Literals are the fixed values that define
modified once declared. themselves.

Constants are defined by using the const


They themselves are the values that are
keyword in C. They store literal values in
assigned to the variables or constants.
themselves.

We cannot determine the address of a literal


We can determine the address of constants.
except string literal.

They are lvalues. They are rvalues.

Example: const int c = 20. Example: 24,15.5, ‘a’, “Geeks”, etc.


Defining Constant using #define Preprocessor

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.

#define const_name value

Example of Constant Macro

// C Program to define a constant using #define

#include <stdio.h>

#define pi 3.14

int main()

printf("The value of pi: %.2f", pi);

return 0;

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:

Constants using const Constants using #define

They are the macros that are replaced by their


They are the variables that are immutable
value.

They are handled by the compiler. They are handled by the preprocessor.

Syntax: const type name = value; Syntax: #define name value

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.

// C Program to change the value of a constant variable

2
#include <stdio.h>

int main()

// defining an integer constant

const int var = 10;

printf("Initial Value of Constant: %d\n", var);

10

11

// defining a pointer to that const variable

12

int* ptr

13

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

14

// changing value

15

*ptr = 500;

16

17

printf("Final Value of Constant: %d\n", var);


18

printf("Accessing through pointer: %d\n", *ptr);

19

return 0;

20

Output

Initial Value of Constant: 10

Final Value of Constant: 500

Accessing through pointer: 500

Related Article – Const Qualifier in C

Const Qualifier in C

Last Updated : 17 Dec, 2024

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

// Defining a constant variable


6

const a = 10;

printf("%d", a);

// Trying to modify the constant variable

10

a = 11;

11

12

return 0;

13

Output

solution.c: In function ‘main’:

solution.c:6:11: warning: type defaults to ‘int’ in declaration of ‘a’ [-Wimplicit-int]

6| const a = 10;

| ^

solution.c:10:11: error: assignment of read-only variable ‘a’

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

 Constant Pointer to Constant

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.

const type* name;


or
typeconst *name;

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.

Examples of Pointer to Constant

Let us see the following examples.

Example 1:

#include <stdio.h>

int main() {

int i = 10;

int j = 20;

// ptr is pointer to constant

const int* ptr = &i;

printf("ptr: %d\n", *ptr);

// error: value pointed cannot be modified

// using the pointer ptr

*ptr = 100;

// This is valid though

ptr = &j;
printf("ptr: %d\n", *ptr);

return 0;

Output

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

./Solution.c:12:10: error: assignment of read-only location '*ptr'

*ptr = 100;

Program where variable i itself is constant.

#include <stdio.h>

int main() {

// i is stored in read only area

int const i = 10;

int j = 20;

//pointer to integer constant

int const* ptr = &i;

printf("ptr: %d\n", *ptr);

// This will throw error

*ptr = 100;

//This is valid valid

ptr = &j;

printf("ptr: %d\n", *ptr);


return 0;

Output

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

./Solution.c:18:10: error: assignment of read-only location '*ptr'

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

Program to show down qualification

#include <stdio.h>

int main() {

int i = 10;

int const j = 20;

// ptr is pointing an integer object

int* ptr = &i;

10

printf("*ptr: %d\n", *ptr);

11
12

// In C, the compiler *may* throw a warning, but

13

// casting is implicitly allowed

14

ptr = &j;

15

16

printf("*ptr: %d\n", *ptr);

17

18

return 0;

19

Output

main.c: In function ‘main’:

main.c:16:9: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-
qualifiers]

16 | ptr = &j;

| ^

*ptr: 10

*ptr: 20

Constant Pointer to Variable

Constant pointer means that the pointer itself is a constant. It means that we cannot change the
pointer to point to another variable.

int* const ptr;

Let’s take a look at an example:

// C program to demonstrate that the value of object pointed


// by pointer can be changed but the pointer can not point

// to another variable

#include <stdio.h>

int main(void)

int i = 10;

int j = 20;

/* constant pointer to integer */

int* const ptr = &i;

printf("ptr: %d\n", *ptr);

*ptr = 100; /* valid */

printf("ptr: %d\n", *ptr);

ptr = &j; /* error */

return 0;

Output

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

./Solution.c:15:9: error: assignment of read-only variable 'ptr'

ptr = &j; /* error */

Constant Pointer to Constant

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.

const int* const ptr;

Let us see with an example:

// C program to demonstrate that value pointed by the


// pointer can not be changed as well as we cannot point the

// pointer to other variables

#include <stdio.h>

int main(void)

int i = 10;

int j = 20;

/* constant pointer to constant integer */

const int* const ptr = &i;

printf("ptr: %d\n", *ptr);

ptr = &j; /* error */

*ptr = 100; /* error */

return 0;

Output

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

./Solution.c:12:9: error: assignment of read-only variable 'ptr'

ptr = &j; /* error */

./Solution.c:13:10: error: assignment of read-only location '*ptr'

*ptr = 100; /* error */

Advantages of const Qualifier

The const qualifier in C has the following advantages:


 Improved Code Readability: By marking a variable as const, you indicate to other
programmers that its value should not be changed, making your code easier to understand
and maintain.

 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

Pointer Value Change Pointing Value Change


Type Declaration (*ptr = 100) (ptr = &a)

Pointer to Variable int * ptr Yes Yes

const int * ptr


Pointer to Constant No Yes
int const * ptr

Constant Pointer to
int * const ptr Yes No
Variable

Different ways to declare variable as constant in C

Last Updated : 10 Jun, 2024

There are many different ways to make the variable as constant in C. Some of the popular ones are:

1. Using const Keyword

2. Using Macros

3. Using enum Keyword


1. Using const Keyword

The const keyword specifies that a variable or object value is constant and can’t be modified at the
compilation time.

Syntax

const data_type variable_name = initial_value;

Example

The below example demonstrates use of the const keyword.

// C program to demonstrate const specifier

#include <stdio.h>

int main()

const int num = 1;

num = 5; // Modifying the value

return 0;

It will throw as error like:


error: assignment of read-only variable ‘num’

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

#define name value

Example

The below example demonstrates use of macros (#define).

// C program to demonstrate the problems

// in 'Macros'

#include <stdio.h>

#define var 5

int main()

printf("%d ", var);

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.

3. Using enum Keyword

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

The below example demonstrates use of the enum keyword.

// C program to illustrate the use of enums to declare

// constant

#include <stdio.h>

// In C internally the default


6

// type of 'var' is int

enum VARS { var = 42 };

// where mytype = int, char, long etc.

10

// but it can't be float, double or

11

// user defined data type.

12

int main()

13

14

printf("The value of var: %d", var);

15

16

return 0;

17

Output

The value of var: 42

Note: The data types of enum are of course limited as we can see in above example.

You might also like