Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

constant data type
c++

What are const primitive data type parameters in C++?

Rabia Zareen

Primitive data type

The data types that are predefined and are supported by programming language are known as primitive data types. For example, the primitive data types for the C++ language are as follows:

  • bool
  • short int
  • int
  • long
  • float
  • double
  • char
Common primitive data types

const primitive data type parameters

Primitive data type parameters can be declared constant.

Syntax

int sum(const int a, const int b)

The following sample code shows the const datatype parameters:

#include <iostream>
using namespace std;
int sum(const int a, const int b)
{
  return a+b;
}
int increment(int a){
  return ++a;
}
//int incrementconst(const int a){
//  return ++a;
//}
int main() {
  int a =10;
  int b=20;
  cout << "Sum is "<<sum(a,b)<<'\n';
  cout<< "Increment is "<<increment(a);
  //cout<< "Constant patrameters increment is "<<incrementconst(a);
  return 0;
}
Const primitive data type parameter

const data type use case

If we want to modify the parameter’s value, then it should not be constant. This is because when we write a parameter with the const keyword, there will be an error while modifying the parameter.

In the above code, we use a non-const parameter that can be modified easily. However, if we use const parameters, the compiler will give an error.

Note: We can uncomment lines 10, 11, 12, and 18 to check the type of error we get when modifying a constant variable.

Compiler error

RELATED TAGS

constant data type
c++

CONTRIBUTOR

Rabia Zareen
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring