Constant in C

In C programming language, a constant is similar to variable but the constant hold only value during the program execution that is value cannot be changed during the course of program lifetime.

This is primary used for such variable for which we do not want to change the value.

This image has an empty alt attribute; its file name is file.png

Creating a constant in C:

In C programming language, constant can be created by using two concepts:

  • Using a ‘const’ keyword
  • Using ‘#define’ preprocessor

Using a ‘const’ keyword:

A constant of any data type can be created by using a const keyword. We prefix the variable declaration with ‘const’ keyword.

Syntax:

const <data_type> <constant_name>
OR
const <data_type> <constant_name> = value;

Example:

#include <stdio.h>

int main()
{
  const int x =10;
  x++;
  printf("\n The value of x is: %d\n", x);

  return 0;
}

Output:

main.c:16:5: error: increment of read-only variable ‘x’
    x++;

Using ‘#define’ preprocessor:

We can also create constants using ‘#define’ preprocessor directive. When we create constant using this preprocessor directive defined globally.

Example:

#include<stdio.h>


#defien  PI  3.14

int main()
{
   int r, area ;
   
   printf("Please enter the radius of circle : ") ;
   scanf("%d", &r) ;
   
   area = PI * (r * r) ;
   
printf("Area of the circle = %d", area) ;

   return 0;
}

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: