Friday, 24 February 2017

Defining Constants

Defining Constants

There are two simple ways in C to define constants:
· Using #define pre-processor
· Using const keyword
The #define Pre-processor
Given below is the form to use #define preprocessor to define a constant:

#define identifier value

The following example explains it in detail:

#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}

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

value of area : 50

The const Keyword

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

const type variable = value;

The following example explains it in detail:

#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result:

value of area : 50

Note that it is a good programming practice to define constants in CAPITALS.

No comments:

Post a Comment