Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
count() in C++ STL
Next article icon

Const keyword in C++

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, the various functions of the const keyword which is found in C++ are discussed. Whenever const keyword is attached with any method(), variable, pointer variable, and with the object of a class it prevents that specific object/method()/variable to modify its data items value.

Constant Variables:

There are certain set of rules for the declaration and initialization of the constant variables:

  • The const variable cannot be left un-initialized at the time of the declaration.
  • It cannot be assigned value anywhere in the program.
  • Explicit value needed to be provided to the constant variable at the time of declaration of the constant variable.

const variable

Below is the C++ program to demonstrate the above concept:

C++
// C++ program to demonstrate the // the above concept #include <iostream> using namespace std;  // Driver Code int main() {      // const int x;  CTE error     // x = 9;   CTE error     const int y = 10;     cout << y;      return 0; } 

Output
10

The error faced for faulty declaration: If you try to initialize the const variable without assigning an explicit value then a compile-time error (CTE) is generated. 

Const Keyword With Pointer Variables:


 Pointers can be declared with a const keyword. So, there are three possible ways to use a const keyword with a pointer, which are as follows:

When the pointer variable point to a const value:

Syntax: 

const data_type* var_name;

Below is the C++ program to implement the above concept: 

C++
// C++ program to demonstrate the // above concept #include <iostream> using namespace std;  // Driver Code int main() {     int x{ 10 };     char y{ 'M' };      const int* i = &x;     const char* j = &y;      // Value of x and y can be altered,     // they are not constant variables     x = 9;     y = 'A';      // Change of constant values because,     // i and j are pointing to const-int     // & const-char type value     // *i = 6;     // *j = 7;      cout << *i << " " << *j; } 

Output
9 A

Explanation: Here in the above case, i and j are two pointer variables that are pointing to a memory location const int-type and char-type, but the value stored at these corresponding locations can be changed as we have done above. 

Otherwise, the following error will appear: If we try to modify the value of the const variable.

When the const pointer variable point to the value:

Syntax:

data_type* const var_name;

Below is the example to demonstrate the above concept:

C++
// C++ program to demonstrate the // above concept #include <iostream> using namespace std;  // Driver Code int main() {     // x and z non-const var     int x = 5;     int z = 6;      // y and p non-const var     char y = 'A';     char p = 'C';      // const pointer(i) pointing     // to the var x's location     int* const i = &x;      // const pointer(j) pointing     // to the var y's location     char* const j = &y;      // The values that is stored at the memory location can     // modified even if we modify it through the pointer     // itself No CTE error     *i = 10;     *j = 'D';      // CTE because pointer variable     // is const type so the address     // pointed by the pointer variables     // can't be changed     // i = &z;     // j = &p;      cout << *i << " and " << *j << endl;     cout << i << " and " << j;      return 0; } 

Output
10 and D 0x7ffe21db72b4 and D

Explanation: The values that are stored in the corresponding pointer variable i and j are modifiable, but the locations that are pointed out by const-pointer variables where the corresponding values of x and y are stored aren't modifiable. 

Otherwise, the following error will appear: The pointer variables are const and pointing to the locations where the x and y are stored if we try to change the address location then we'll face the error.

When const pointer pointing to a const variable:

Syntax:

const data_type* const var_name;

Below is the C++ program to demonstrate the above concept:

C++
// C++ program to demonstrate // the above concept #include <iostream> using namespace std;  // Driver code int main() {     int x{ 9 };      const int* const i = &x;      // *i=10;     // The above statement will give CTE     // Once Ptr(*i) value is     // assigned, later it can't     // be modified(Error)      char y{ 'A' };      const char* const j = &y;      // *j='B';     // The above statement will give CTE     // Once Ptr(*j) value is     // assigned, later it can't     // be modified(Error)      cout << *i << " and " << *j;      return 0; } 

Output
9 and A

Explanation: Here, the const pointer variable points to the const variable. So, you are neither allowed to change the const pointer variable(*P) nor the value stored at the location pointed by that pointer variable(*P).

Otherwise, the following error will appear: Here both pointer variable and the locations pointed by the pointer variable are const so if any of them is modified, the following error will appear:

Pass const-argument value to a non-const parameter of a function cause error: Passing const argument value to a non-const parameter of a function isn't valid it gives you a compile-time error.

Below is the C++ program to demonstrate the above concept:

C++
// C++ program to demonstrate // the above concept #include <iostream> using namespace std;  int foo(int* y) { return *y; }  // Driver code int main() {     int z = 8;     const int* x = &z;     cout << foo(x);     return 0; } 

Output: The compile-time error that will appear as if const value is passed to any non-const argument of the function then the following compile-time error will appear:

Additionally, passing const pointer will not result in any error because another pointer is created which also points to the same memory location.

C++
//C++ program to demonstrate the above concept #include <iostream> using namespace std;  void printfunc(int* ptr) {     cout << "Value :" << *ptr << endl;     cout << "Address of ptr :" << &ptr << endl; } //Driver Code int main() {     int x = 10;     int* const i = &x;     printfunc(i);     cout << "Address of i :" << &i << endl; } 

Output
Value :10 Address of ptr :0x7ffff0189b48 Address of i :0x7ffff0189b70 

The code is executed without any errors and the two pointers have different addresses.

In nutshell, the above discussion can be concluded as follows:

1. int value = 5;         // non-const value

2. const int *ptr_1 = &value;      // ptr_1 points to a "const int" value, so this is a pointer to a const value.

3. int *const ptr_2 = &value;        // ptr_2 points to an "int", so this is a const pointer to a non-const value.

4. const int *const ptr_3 = &value;   // ptr_3 points to a "const int" value, so this is a const pointer to a const value.

Constant Methods:

Like member functions and member function arguments, the objects of a class can also be declared as const. An object declared as const cannot be modified and hence, can invoke only const member functions as these functions ensure not to modify the object.

Syntax:

const Class_Name Object_name;
  • When a function is declared as const, it can be called on any type of object, const object as well as non-const objects.
  • Whenever an object is declared as const, it needs to be initialized at the time of declaration. However, the object initialization while declaring is possible only with the help of constructors.

There are two ways of a constant function declaration:

Ordinary const-function Declaration:

const void foo()
{
//void foo() const Not valid
}
int main()
{
foo();
}

A const member function of the class:

class
{
void foo() const
{
//.....
}
}

Below is the example of a constant function:

C++
// C++ program to demonstrate the // constant function #include <iostream> using namespace std;  // Class Test class Test {     int value;  public:     // Constructor     Test(int v = 0) { value = v; }      // We get compiler error if we     // add a line like "value = 100;"     // in this function.     int getValue() const { return value; }      // a nonconst function trying to modify value     void setValue(int val) { value = val; } };  // Driver Code int main() {     // Object of the class T     Test t(20);      // non-const object invoking const function, no error     cout << t.getValue() << endl;      // const object     const Test t_const(10);      // const object invoking const function, no error     cout << t_const.getValue() << endl;      // const object invoking non-const function, CTE     // t_const.setValue(15);      // non-const object invoking non-const function, no     // error     t.setValue(12);      cout << t.getValue() << endl;      return 0; } 

Output
20 10 12

The following error will if you try call the non-const function from a const object

calling-non-const-function-from-const-object


Constant Function Parameters And Return Type:

A function() parameters and return type of function() can be declared as constant. Constant values cannot be changed as any such attempt will generate a compile-time error.

Below is the C++ program to implement the above approach:

C++
// C++ program to demonstrate the // above approach #include <iostream> using namespace std;  // Function foo() with variable // const int void foo(const int y) {     // y = 6; const value     // can't be change     cout << y; }  // Function foo() with variable int void foo1(int y) {     // Non-const value can be change     y = 5;     cout << '\n' << y; }  // Driver Code int main() {     int x = 9;     const int z = 10;      foo(z);     foo1(x);      return 0; } 

Output
10 5


 Explanation: The following error will be displayed if the statement y = 6 is used in the function foo(): 

  • // y = 6; a const value can't be changed or modified.

For const return type: The return type of the function() is const and so it returns a const integer value to us. Below is the C++ program to implement the above approach: 

C++
// C++ program for the above approach #include <iostream> using namespace std;  const int foo(int y) {     y--;     return y; }  int main() {     int x = 9;     const int z = 10;     cout << foo(x) << '\n' << foo(z);      return 0; } 

Output
8 9

The value returned will be a constant value.

Also, there is no substantial issue to pass const or non-const variable to the function as long as we are passing it by value because a new copy is created. The issue arises when we try to pass the constant variable by reference to the function whose parameter is non-constant. This disregards the const qualifier leading to the following error:

passing-const-argument-to-non-const-parameter-by-reference

For const return type and const parameter: Here, both return type and parameter of the function are of const types. Below is the C++ program to implement the above approach:

C++
// C++ program for the above approach #include <iostream> using namespace std;  const int foo(const int y) {     // y = 9; it'll give CTE error as     // y is const var its value can't     // be change     return y; }  // Driver code int main() {     int x = 9;     const int z = 10;     cout << foo(x) << '\n' << foo(z);      return 0; } 

Output
9 10

Explanation: Here, both const and non-const values can be passed as the const parameter to the function, but we are not allowed to then change the value of a passed variable because the parameter is const. Otherwise, we'll face the error as below: 

// y=9; it'll give the compile-time error as y is const var its value can't be changed.


Next Article
count() in C++ STL
author
madhav_mohan
Improve
Article Tags :
  • Technical Scripter
  • C++
  • CPP-Basics
  • C++-const keyword
Practice Tags :
  • CPP

Similar Reads

  • Static Keyword in C++
    The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses. In C++, a static keyword can be used in the following context: Table of Content Static Variables in a FunctionStatic Member Var
    5 min read
  • C++ Keywords
    Keywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
    2 min read
  • order_of_key() in C++
    The order_of_key() is a builtin function of Ordered Set which is a Policy Based Data Structure in C++. Policy-based data structures are not part of the C++ standard library but g++ compiler supports them. Ordered set is a policy based data structure in g++ that keeps the unique elements in sorted or
    3 min read
  • count() in C++ STL
    In C++, the count() is a built-in function used to find the number of occurrences of an element in the given range. This range can be any STL container or an array. In this article, we will learn about the count() function in C++. Let’s take a quick look at a simple example that uses count() method:
    3 min read
  • unordered_map count() in C++
    The unordered_map::count() is a builtin method in C++ which is used to count the number of elements present in an unordered_map with a given key. Note: As unordered_map does not allow to store elements with duplicate keys, so the count() function basically checks if there exists an element in the un
    2 min read
  • Using Keyword in C++ STL
    The using keyword in C++ is a tool that allows developers to specify the use of a particular namespace. This is especially useful when working with large codebases or libraries where there may be many different namespaces in use. The using keyword can be used to specify the use of a single namespace
    6 min read
  • Conversion Operators in C++
    In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading
    4 min read
  • cout in C++
    In C++, cout is an object of the ostream class that is used to display output to the standard output device, usually the monitor. It is associated with the standard C output stream stdout. The insertion operator (<<) is used with cout to insert data into the output stream. Let's take a look at
    2 min read
  • constinit Specifier in C++ 20
    The constinit specifier is a new feature that is introduced in C++ 20 that allows us to declare a variable with static storage duration. In this article we will discuss the constinit specifier, its usage, advantages, and limitations. What is constinit Specifier? The constinit specifier is used to ma
    3 min read
  • Const member functions in C++
    Constant member functions are those functions that are denied permission to change the values of the data members of their class. To make a member function constant, the keyword const is appended to the function prototype and also to the function definition header. Like member functions and member f
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences