Home > Article > Backend Development > What are constants in C language? Can you give an example?
Constants are also called variables. Once defined, their values will not change during program execution. Therefore, we can declare a variable as a constant referencing a fixed value. It is also called text. Constants must be defined using the Const keyword.
The constant syntax used in C programming language is as follows-
const type VariableName; (or) const type *VariableName;
Different types of constants used in C programming language The constants look like this:
Integer constants - For example: 1,0,34,4567
Floating point constants - For example: 0.0, 156.89, 23.456
Octal and hexadecimal constants - For example: Hexadecimal: 0x2a, 0xaa .. Octal: 033, 024,..
Character constants - For example: 'a', 'B', 'x'
String constants - Example: "TutorialsPoint"
The types of constants are also shown in the diagram below:
The following is a C program for determining the value of a number:
Demonstration
#include<stdio.h> int main(){ const int number=45; int value; int data; printf("enter the data:"); scanf("%d",&data); value=number*data; printf("The value is: %d",value); return 0; }
When the above program is executed, the following results are produced -
enter the data:20 The value of number is: 900
In the above program, if we try to change the value of a number declared as a constant, it displays an error.
Below is a C program that displays an error if we try to change the const value.
#include<stdio.h> int main(){ const int number=45; int data; printf("enter the data:"); scanf("%d",&data); number=number*data; printf("The value of number is: %d",number); return 0; }
When the above program is executed, the following results are produced -
error
The above is the detailed content of What are constants in C language? Can you give an example?. For more information, please follow other related articles on the PHP Chinese website!