Constants in C Programing with Example
Constants:
In C programming language, a constant are often of any data type like integer, floating-point, character, string and double ,etc.
Creating constants in C
Constant can be created using two concepts.
Using the 'const' keyword-
We create a constant of any data type using 'const' keyword. To create a constant , we prefix the variable declaration with 'const' keyword.
Syntax
const datatype constantName;
or
const datatype constantName=value;
Example:
const int c=10;
Here 'x' is a integer constant with fixed value 10.
Q.N. write code for const and try to change value of contant and show error.
code_
#include<stdio.h>
#include<conio.h>
void main()
{
int i=9;
const int x=10;
i=15;
x=100; // give an error
printf("i=%d\nx=%d",i,x);
getch();
}
ouput: Error (constant value cannot be changed)
Using "#define" preprocessor-
We can also create constants using "#define" preprocessor directive. When create a constant using this preprocessor directive it must be defined at the beginning of the program (because all the preprocessor directives must be written before the global declaration).
Syntax:
#define CONSTANTNAME value
Q.N. find area of circle using constant function definition
#define PI 3.14;
Here ,PI is a constant with value 3.14;
Program:
#include<stdio.h>
#include<conio.h>
#define PI 3.14
void main()
{
int r;
float area;
printf("Enter the radius of circle:");
scanf("%d",&r);
area= PI*r*r;
printf("Area of the circle=%f",area);
}
output:
Enter the radius of circle:5
Area of the circle=78.500000
--------------------------------
Comments
Post a Comment