Welcome to Home.

Thursday, October 10, 2019

C | Constants

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition. 

Defining Constants 


There are two simple ways in C to define constants −

-> Using #define preprocessor. 
-> Using const keyword.

For Example:

 


#include<stdio.h>

#define HEIGHT 20
#define WIDTH 30
#define FILE_NAME "config.txt"

void main()
{
    const int height = 20;
    const int width  = 30;
    const char name[] = "SAROJ";
    const char file_name[] = "config.txt";
 
    printf("Height : %d",HEIGHT);
    printf("WIDTH  : %d",WIDTH);
    printf("FILE_NAME   : %s",FILE_NAME);
}


Here in this program, constant is declared in two ways, one is by using preprocessor directive called #define and another is like normal variable declaration but const keyword is used in front of it. Also note that, In C programming language, the constant name is always written in capital letter.

No comments:

Post a Comment