Define constant variables in C++ header

Hello readers! In this tutorial, we are going to learn how we can define constant variables in the C++ header file. In C++ constant variables are defined as the types of variables whose value can’t be changed once they are defined, they remain fixed all throughout the program.

In C++ a variable can be declared constant by 2 ways:

  • Using #define keyword method
Syntax:- #define identifier_name value

Example- #define var3 290

  •  By using const keyword method
 Syntax:- const datatype identifier_name = value

Example- const int var8 = 300

C++ Code: constant variables in C++ header

Refer to the code below to see both the ways :

Refer to the comments in the code for better understanding

#include <iostream>
#define var1 89    
const int var2=340;   //using const keyword method
int main()
{
   std::cout<<var1<<" "<<var2; //using std::cout for output
}

Output:

89 340

Explanation of the code:

Using  #define declare a constant variable with constant value. Now using const keyword declare another constant variable. Declare the main function . The output values of both the variables will be printed using std::cout.


That’s all for the tutorial. Hope you liked it!

Happy learning!

Leave a Reply

Your email address will not be published.