2.6.Defining Constants

Constant used for stored any values like variable, but constant can not change any values while the process executed.

There are two simple ways in C++ to define constants such:

  • Define Constant

There are many steps for declaring constants like:

– Must be declaring above of main function

– Must be stating declare with symbol (#)  and keyword define like #define

– No need initialize symbol (=), semicolon symbol (;)

Syntax: Define constants declaration form

      #include<iostream.h>
      #define pi 3.14
      void main()
      {
           statements... 
      }

        Example: Define constants example

      #include<iostream.h>
      #include<conio.h>
      #define pi 3.14
      void main()
      {
                float radius,area;
                cout<<"Enter Radius: ";
                cin>>radius;
                area=radius*radius*pi;
                cout<<"Area Of Cicle: "<<area;
                getch();
       }
  • Memory Constant

Memory constants should be followed style of variable declaration just include const before of data type.

Syntax: Memory constants declaration form

      #include<iostream.h>
      void main()
      {
                const float pi=3.14;
                statements... 
      }

       Example: Memory constants example

      #include<iostream.h>
      #include<conio.h>
      void main()
      {
                const pi=3.14;
                float radius,area;
                cout<<"Enter Radius: ";
                cin>>radius;
                area=radius*radius*pi;
                cout<<"Area Of Cicle: "<<area;
                getch();
       }

 

Suggest Edit