Constants in C

In c, constants are fixed values which cannot be modified during program execution. const keyword is used to make a variable constant. Constant variables must be initialized, without initialization it gives error.

Syntax

const data_type variable_name = value;

Example

#include<stdio.h>
#include<conio.h>

void main(){
	const int MAXSPEED = 100;
	printf("%d", MAXSPEED);
}

C constants types

According to c data types, constants are divided into following four types.

  1. Integer constant
  2. Float constant
  3. Character constant
  4. String constant

Integer constant

A constant with only whole numbers called integer constant. This constant is declared using int data type. Its range is from 0 to 9.

#include<stdio.h>
#include<conio.h>

void main(){
  const int no  = 100;
  printf("%d", no);
}

Float constants

It contains values with fractional part means value with decimal part. float data type is used to declare float constants.

#include<stdio.h>
#include<conio.h>

void main(){
  const float PI  = 3.14;
  printf("%f", PI);
}

Character constant

A character constant holds a character value. char data type is used to declare char constants.

#include<stdio.h>
#include<conio.h>

void main(){
  const char a  = 'z';
  printf("%c", a);
}

String constant

A constant which holds a string value inside double quotes.

#include<stdio.h>
#include<conio.h>

void main(){
  const char s[]  = "Hello world";
  printf("%s", s);
}