Scenario Analysis: "const keywords in C Language"

Source: Internet
Author: User

Const in C language has always been a pain point for beginners in C language. This is because const has different functions in different locations and has different roles in different scenarios. This leaves beginners confused. Today, I will study const with you to make every role "deeply rooted in the hearts of the people "!

========================================================== ========================================================== ====================

Scenario 1: The simplest const usage

 

# Include <stdio. h>
Int main ()
{
Int const;
A = 5;
Printf ("a = % d \ n", );
Return 0;
} If the c file is compiled, an error is returned:

1071. c: In function 'main ':
1071. c: 5: error: assignment of read-only variable 'A'

Obviously, this is what const is doing, because the variable declared const cannot be modified!

If you change the source code to the following, there is no problem!

# Include <stdio. h>
Int main ()
{
Int const a = 5;
Printf ("a = % d \ n", );
Return 0;
} Conclusion: the variables declared by const must be initialized and assigned values. If you miss this opportunity and want to assign values to the variables declared by const later, you can leave it empty! Remember ~

PS: int const and const int are the same thing. "reverse writing" is acceptable. Don't be dizzy later. However, we still need to keep an eye on it. When const and pointer get together, this "Inverted write" rule may not be true.

========================================================== ========================================================== ====================

Scenario 2: Why is const invented?

Before the emergence of const, developers always used # define VAR 100 to define class constants with special purposes. However, such definitions have some disadvantages. Therefore, const came into being. After that, developers can use const int VAR = 100; To define class constants.

As to why # define has its disadvantages, readers should go to google. :)

========================================================== ========================================================== ====================

Scenario 3: The combination of const and pointer is a nightmare!

Can you tell these statements clearly:

Const int *;
Int const *;
Int * const;
Const int * const A; if it is A bit dizzy, give their explanations first, and then continue to look at the subsequent situation analysis.

Const int * A; // modify the object to which A points. A is variable, and A is not variable.
Int const * A; // modify the object to which A points. A is variable, and A is variable.
Int * const A; // modifier pointer A, A is immutable, and A points to the object is variable
Const int * const A; // The objects pointed to by pointers A and A are not changeable.

========================================================== ========================================================== ====================

Scenario 4: const int *

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Const int * A = & num;
Printf ("result = % d \ n", * );
Return 0;
} The compilation result is:

[Rocrocket @ wupengchong const_test] $ cc test1.c
[Rocrocket @ wupengchong const_test] $./a. out
Result = 12

Next, we add (* A) ++ to the Code. This statement:

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Const int * A = & num;
(* A) ++;
Printf ("result = % d \ n", * );
Return 0;
} Compile the c file:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
Test1.c: In function 'main ':
Test1.c: 6: error: increment of read-only location '*'
As you can see, an error is reported, indicating that "* A" is read-only and cannot be modified.

Let's modify the source code as follows:

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int tmp= 100;
Const int * A = & num;
A = & tmp;
Printf ("result = % d \ n", * );
Return 0;
} The compilation result is:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
[Rocrocket @ wupengchong const_test] $./a. out
Result = 100.

Well, if you have carefully read these few small programs, you can come to a conclusion on your own!

Conclusion: If the const int * A is declared, the value can be modified, but * A cannot be modified. In more general terms, the pointer can point to an integer at will, but it cannot be modified as long as the integer variable targeted by A is referenced by *.

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int tmp= 100;
Const int * A = & num;
A = & tmp;
Tmp = 3;
Printf ("result = % d \ n", * );
Return 0;
} The result of compilation and execution is:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
[Rocrocket @ wupengchong const_test] $./a. out
Result = 3

Conclusion 2: even if A points to tmp, although I cannot modify * A, I can still use tmp to modify this value, regardless of the existence of *. Haha www.2cto.com

========================================================== ========================================================== ====================

Scenario 5: int * const

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int * const A = & num;
Printf ("result = % d \ n", * );
Return 0;
} The compilation result is:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
[Rocrocket @ wupengchong const_test] $./a. out
Result = 12

Let's slightly modify the source code:

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int tmp= 100;
Int * const A = & num;
A = & tmp;
Printf ("result = % d \ n", * );
Return 0;
} An error was reported during compilation:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
Test1.c: In function 'main ':
Test1.c: 7: error: assignment of read-only variable 'A'
[Rocrocket @ wupengchong const_test] $ cat test1.c

It can be seen that the value of A itself cannot be changed.

Continue to modify the source code as follows:

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int * const A = & num;
(* A) = 100;
Printf ("result = % d \ n", * );
Return 0;
} The compilation result is:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
[Rocrocket @ wupengchong const_test] $./a. out
Result = 100.

It can be seen that (* A) can be changed.

Conclusion: int * const A; // const modifies the pointer A, A is immutable, and A points to the object is mutable.

========================================================== ========================================================== ====================

Scenario 6: const int * const A; // The objects pointed to by pointer A and pointer A are unchangeable.

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int const * const A = & num;
(* A) = 100;
Printf ("result = % d \ n", * );
Return 0;
} An error will be reported during compilation:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
Test1.c: In function 'main ':
Test1.c: 6: error: assignment of read-only location '*'

Change the source code:

[Rocrocket @ wupengchong const_test] $ cat test1.c

# Include <stdio. h>
Int main ()
{
Int num = 12;
Int tmp= 100;
Int const * const A = & num;
A = & tmp;
Printf ("result = % d \ n", * );
Return 0;
} The compilation still reports an error:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test1.c
Test1.c: In function 'main ':
Test1.c: 7: error: assignment of read-only variable 'A'

Well, the conclusion is obvious: const int * const A; // The objects pointed to by pointer A and pointer A are immutable.

Of course, const int * const A; and int const * const A = & num; are equivalent!

Scenario 7: What if const is used in function parameters? Is it complicated?

The answer is NO! It is not complicated at all.

Let's take a look at this function cast: int addnum (const int num, int a, int B );

The first parameter in this function declaration is const int num, which indicates that if I call this function, the first real parameter cannot be modified after it is passed to the addnum function! It's that simple.

Let's give an example to make it clearer:

[Rocrocket @ wupengchong const_test] $ cat test2.c

# Include <stdio. h>
Int addto (const int num, int a, int B)
{
If (num = 1 ){
Return a + B;
} Else {
Return 0;
}
}
 
Int main (){
Int num = 100;
Int a = 12, B = 22;
Int res;
Num = 1;
Res = addto (num, a, B );
Printf ("res = % d \ n", res );
Return 0;
} The compilation result is:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test2.c
[Rocrocket @ wupengchong const_test] $./a. out
Res = 34

If I modify it, the compilation will fail:

[Rocrocket @ wupengchong const_test] $ cat test2.c

# Include <stdio. h>
Int addto (const int num, int a, int B)
{
If (num = 1 ){
Num = 3;
Return a + B;
} Else {
Return 0;
}
}
 
Int main (){
Int num = 100;
Int a = 12, B = 22;
Int res;
Num = 1;
Res = addto (num, a, B );
Printf ("res = % d \ n", res );
Return 0;
} The compilation error is:

[Rocrocket @ wupengchong const_test] $! Cc
Cc test2.c
Test2.c: In function 'addto ':
Test2.c: 5: error: assignment of read-only location 'num'

It can be seen that the variable declared as const in the function cannot be modified! Haha ~

Const is actually not difficult. It's Okay To understand several small examples in this article!

Except for the parameters required to be passed as const, there is nothing to add to the declared object, but it should not be modified logically. It should be a constant object and not declared as const, it must be maintained by the programmer himself to remember that the variable should not be modified. Even if you accidentally modify the variable, the compiler will not report an error.
In addition, const and the declaration of common variables are different from header files. In short, these are related to your specific program writing plan. const is just a convenient tool for programming and programming, it can make the program clearer. If I just don't like to use it, or I like to use all the variables in the end, there's nothing wrong with it.
 


From c'est la vie

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.