Home > Backend Development > C++ > What are constants in C language? Can you give an example?

What are constants in C language? Can you give an example?

WBOY
Release: 2023-08-28 22:45:07
forward
1696 people have browsed it

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.

Grammar

The constant syntax used in C programming language is as follows-

const type VariableName;
(or)
const type *VariableName;
Copy after login

Different types of constants

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:

What are constants in C language? Can you give an example?

Example 1

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;
}
Copy after login

Output

When the above program is executed, the following results are produced -

enter the data:20
The value of number is: 900
Copy after login

In the above program, if we try to change the value of a number declared as a constant, it displays an error.

Example 2

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;
}
Copy after login

Output

When the above program is executed, the following results are produced -

error
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template