C++ Constants

WHAT IS CONSTANTS?

The difference between variables and constants is that variables can change their value at any time but constants can never change their value.
Tips for Constant variable
  •     Constants are also called literals.
  •     Constants can be any of the data type.
  •     It is considered best practice to define constants using only upper-case names.
There are two method for constant variable in C++

1.    By using const keyword 

Syntax:  
const type constant_name;

Example with const keyword
#include <iostream>
using namespace std;
int main()
{
  const float e = 3.1415; //constant variable
  cout<<"value="<<(e*10);
  return 0;
}

        2.    By using #define Preprocessor keyword 

Syntax: 
#define constant_name;

Example with #define keyword
#include <iostream>
using namespace std;
#define e 3.1415; //constant variable
int main()
{
  cout<<"value="<<(e*10);
  return 0;

}


<< C++Data Types            --         C++ Operators>> 

No comments:

Post a Comment