C Basics

Defining Constants

User Rating:  / 2
PoorBest 

There are two simple ways in C to define constants:

1.    Using #define preprocessor.

2.    Using const keyword.

The #define Preprocessor

Following is the form to use #define preprocessor to define a constant:

#define identifier value

Following example explains it in detail:

 
#include <stdio.h>
#define PI 3.14   
int main()
{
   int radius = 6; 
   float area;
   area = PI * radius * radius;
   printf("Value of area : %d", area);
   return 0;
}

When the above code is compiled and executed, it produces following result:

value of area: 113.04

 

The const Keyword

You can use const prefix to declare constants with a specific type as follows:

const type variable = value;

Following example explains it in detail:

#include <stdio.h>
#define PI 3.14   
int main()
{
   int radius = 6; 
   float area;
   area = PI * radius * radius;
   printf("Value of area : %d", area);
   return 0;
}

When the above code is compiled and executed, it produces following result:

value of area : 150

Note: - Always define constants in CAPITAL. (Good Programming Practise)

 

 
 
 

                                                                                          About Us  ||  Contact Us  ||  Terms & Conditions  ||  Privacy Policy 

Referral Banners