Constant in C/C++
Constant is a variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc.Every constant has some range. The integers that is too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under signed bit the range of an int, varies from -128 to +127 and under unsigned bit int varies from 0 to 255.
Defining Constants
In C program we can define constants in two ways as shown below:- Using #define preprocessor directive
- Using a const keyword.
Using #define preprocessor directive : This directive used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:
#define VarName value
where Varname is the name given to constant and value is any value assigned to it.
Below is the C program to explain how to use #define to declare constants:
#include<stdio.h>
#define floatVal 4.5
#define charVal 'G'
int main()
{
printf("Integer Constant: %d\n",val);
printf("Floating point Constant: %f\n",floatVal);
printf("Character Constant: %c\n",charVal);
return 0;
}
Floating point Constant: 4.500000
Character Constant: G
int main()
{
const int intVal = 10; // int constant
const float floatVal = 4.14; // Real constant
const char charVal = 'A'; // char constant
const char stringVal[10] = "ABC"; // string constant
printf("Integer constant :%d \n", intVal );
printf("Floating point constant : %f \n", floatVal );
printf("Character constant : %c \n", charVal );
printf("String constant : %s \n", stringVal);
return 0;
}
Floating point constant : 4.140000
Character constant : A
String constant : ABC
{
char *str;
/* Stored in read only part of data segment */
str = "GfG";
/* Problem: trying to modify read only memory */
*(str+1) = 'n';
return 0;
}
No comments:
Post a Comment
Thank you for your Time. Keep Learning