Water drop stone wearing C language correctly using const

xiaoxiao2021-03-06  22

Basic explanation

Const is a keyword of a C language that defines a variable that is not allowed to be changed. Using const can improve the robustness of the program to a certain extent, in addition, when watching others code, clear understanding of the role of Const, there are some helps to understand the other party.

Although this sounds very simple, in fact, the use of Const is also a subtle place in the C language, where is it? Please see the following questions.

Problem: Const variable & constant

Why do I use a const variable to initialize the array in justice, ANSI C's compiler reports an error?

Const int N = 5; int a [n];

Answer and analysis:

1) This problem discusses the difference between "constant" and "read-only variable". Constants are definitely read-only, such as 5, "ABC", etc., must be read-only because there is no place to store its value at all, and of course it is not able to modify it. The "read-only variable" is a place to store it in memory, but this value is defined by the compiler that is not allowed to be modified. C Language Keyword Const is used to qualify a variable that is not allowed to be changed. Qualifier. The variable N is modified as a read-only variable in the above code, but it is not a constant. The dimension must be "constant" when the array definitions specify the array definitions, and "read-only variable" is not possible.

2) Defining a constant, this way is pair), in fact, according to the compilation process and memory allocation, this usage should be reasonable, just the provisions of the ANSI C pairs to array.

3), then what is the constant in the ANSI C language? The answer is an enum type and #define macro, both of which can be used to define constants.

转载请注明原文地址:https://www.9cbs.com/read-42714.html

New Post(0)