Home >>C Tutorial >Constants in C

Constants in C

Constants in C

The Constants in C language is basically a value or variable that can't be changed in the program, here is an example for your understanding: 10, 20, 'a', 3.4, "c programming" etc.

There are various types of constants in the C programming language.

Here are the list of constants present in C along with an example:

Constant Example
String Constant "C", "A program", "P in phptpoint"
Decimal Constant 11, 50, 550 etc.
Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.
Real or Floating-point Constant 10.1, 80.2, 950.6 etc.
Octal Constant 012, 031, 095 etc.
Character Constant 'b', 'c', 'y' etc.

Defining the constants in C

There are generally two ways by which a constant can be defined in the C programming:

1. const keyword

2. #define preprocessor

Const keyword

To define a constant in C programming, the const keyword is used.

Here is the syntax for the same:

const float PI=3.14;  

Note :Please note that the value of PI variable cannot be changed.

Here is an example depicting the same:

#include<stdio.h>   
int main()
{    
    const float PI=3.14;    
    printf("The value of PI is: %f",PI);    
    return 0;  
}     
Output : The value of PI is: 3.140000

In case, the user try to change the value of PI then a compile time error will be rendered. Here is an example depicting the same:

#include<stdio.h>    
int main()
{    
const float PI=3.14;     
PI=4.5;    
printf("The value of PI is: %f",PI);    
return 0;  
}     
Output :Compile Time Error: Cannot modify a const object

define preprocessor in C programming

The #define preprocessor have the same function as of the const keyword i.e to define constant.


Popular Tutorials