首页 > 编程知识 正文

c语音编程语言什么,c编程语言常见问题

时间:2023-05-04 23:23:21 阅读:183286 作者:2752

c语言 const常量

const is a keyword in C language, it is also known as type qualifier (which is to change the property of a variable). const is used to define a constant whose value may not be changed during the program execution. It prevents the accidental changes of the variable.

const是C语言中的关键字,也称为类型限定符 (用于更改变量的属性)。 const用于定义一个常量,其值在程序执行期间不得更改。 这样可以防止变量的意外更改。

Consider these two definitions,

考虑这两个定义,

int value1 = 10;const int value2 = 20;

Here, value1 is an integer variable, the value of value1 can be changed any time during the run time. But, the value2 is an integer constant, and the value of value2 cannot be changed during the run time.

这里, value1是一个整数变量,在运行期间可以随时更改value1的值。 但是, value2是一个整数常量,并且在运行期间无法更改value2的值。

Here, value1 is an integer variable while value2 is an integer constant.

此处, value1是整数变量,而value2是整数常量。

定义一个常数 (Defining a constant)

The const keyword is used to define a constant, include the keyword const before the data type or after the data type, both are valid.

const关键字用于定义常量,在数据类型之前或之后的关键字const都有效。

const data_type constant_name = value;or data_type const constant_name = value;

Does a constant occupy memory?

常量会占用内存吗?

Yes, a constant always occupies memory at compile time. In the above statements, value2 will take sizeof(int) bytes (that maybe 2, 4, or 8 according to the system architecture) in the memory.

是的 ,一个常量总是在编译时占用内存。 在上面的语句中,value2将在内存中占用sizeof(int)个字节(根据系统体系结构可能是2、4或8个字节)。

C程序演示常量示例 (C program to demonstrate the example of constants) #include <stdio.h>int main(){ const int a = 10; //integer constant const float b = 12.3f; // float constant const char c = 'X'; // character constant const char str[] = "Hello, world!"; // string constant // printing the values printf("a = %dn", a); printf("b = %fn", b); printf("c = %cn", c); printf("str = %sn", str); return 0;}

Output:

输出:

a = 10b = 12.300000c = Xstr = Hello, world!

What does happen, if we try to change the value of a constant?

如果我们尝试更改常量的值,会发生什么?

If we try to change the value of a constant, the compiler produces an error that constant is read-only.

如果我们尝试更改常数的值,则编译器会产生一个错误,指出该常数是只读的。

Let's consider this example,

让我们考虑这个例子,

#include <stdio.h>int main(){ const int a = 10; //integer constant // printing the value printf("a = %dn", a); // changing the values a = 20; // again, printing the value printf("a = %dn", a); return 0;}

Output:

输出:

main.c: In function ‘main’:main.c:11:7: error: assignment of read-only variable ‘a’ a = 20; ^

See the output – a is an integer constant here, and when we try to change it, the error is there.

看到输出- 一个是一个整型常量这里,当我们试图改变它,错误是存在的。

翻译自: https://www.includehelp.com/c/const-in-c-programming.aspx

c语言 const常量

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。