Constant in C | IndianTechnoEra - IndianTechnoEra
Latest update Android YouTube

Constant in C | IndianTechnoEra

constant in c it2edu, literal , programming, coding, code with harry, simple coding basics of c language
Admin

Constant in C | IndianTechnoEra 



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.

Constant

Example

Decimal Constant

10, 20, 450 etc.

Real or Floating-point Constant

10.3, 20.2, 450.6 etc.

Octal Constant

021, 033, 046 etc.

Hexadecimal Constant

0x2a, 0x7b, 0xaa etc.

Character Constant

'a', 'b', 'x' etc.

String Constant

"c", "c program", "c in javatpoint" etc.

 

Methods to define constant

There are two ways to define constant in C

1.       const keyword

2.       #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.

const float PI=3.14; 

Now, the value of PI variable can't be changed.

#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

 

If you try to change the the value of PI, it will render compile time error.

Example:

#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

 

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive later.

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:                 #define token value 

Example:

#include <stdio.h> 

#define PI 3.14 

main() { 

   printf("%f",PI); 

Output:

3.140000

 

 

Example of #define to create a macro.

 

#include <stdio.h> 

#define MIN(a,b) ((a)<(b)?(a):(b)) 

void main() { 

   printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));   

Output:

Minimum between 10 and 20 is: 10

 

Visit here for: #define preprocessor directive.

  

Post a Comment

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.