1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > c语言 const常量_C编程中的常量(const)

c语言 const常量_C编程中的常量(const)

时间:2021-06-29 07:12:26

相关推荐

c语言 const常量_C编程中的常量(const)

c语言 const常量

constis a keyword in C language, it is also known as type qualifier (which is to change the property of a variable).constis 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,value1is an integer variable, the value ofvalue1can be changed any time during the run time. But, thevalue2is an integer constant, and the value ofvalue2cannot be changed during the run time.

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

Here,value1is an integer variable whilevalue2is an integer constant.

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

定义一个常数 (Defining a constant)

Theconstkeyword is used to define a constant, include the keywordconstbefore 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, aconstantalways occupies memory at compile time. In the above statements, value2 will takesizeof(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 constantconst float b = 12.3f; // float constantconst char c = 'X'; // character constantconst char str[] = "Hello, world!"; // string constant// printing the valuesprintf("a = %d\n", a);printf("b = %f\n", b);printf("c = %c\n", c);printf("str = %s\n", 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 valueprintf("a = %d\n", a);// changing the valuesa = 20;// again, printing the valueprintf("a = %d\n", 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 –ais an integer constant here, and when we try to change it, the error is there.

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

翻译自: /c/const-in-c-programming.aspx

c语言 const常量

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。