Constants in c

Constants in C

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.
There are different types of constants in C programming.

List of Constants in C

ConstantExample
Decimal Constant10, 20, 450 etc.
Real or Floating-point Constant10.3, 20.2, 450.6 etc.
Octal Constant021, 033, 046 etc.
Hexadecimal Constant0x2a, 0x7b, 0xaa etc.
Character Constant'a', 'b', 'x' etc.
String Constant"c", "c program", "c in javatpoint" etc.

2 ways to define constant in C

There are two ways to define constant in C programming.
  1. const keyword
  2. #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.
  1. const float PI=3.14;  
Now, the value of PI variable can't be changed.
  1. #include<stdio.h>    
  2. int main(){    
  3.     const float PI=3.14;    
  4.     printf("The value of PI is: %f",PI);    
  5.     return 0;  
  6. }     
Output:
The value of PI is: 3.140000
If you try to change the the value of PI, it will render compile time error.
  1. #include<stdio.h>    
  2. int main(){    
  3. const float PI=3.14;     
  4. PI=4.5;    
  5. printf("The value of PI is: %f",PI);    
  6.     return 0;  
  7. }     
Output: Compile Time Error: Cannot modify a const object






C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.
Syntax:
  1. #define token value  
Let's see an example of #define to define a constant.
  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  
Output:
3.140000
Let's see an example of #define to create a macro.
  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  
Output:
Minimum between 10 and 20 is: 10

Comments

Popular posts from this blog

Features of C Language

Flow of C program

Types of LOOPS