Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use const and volatile in C language

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use const and volatile in C language". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use const and volatile in C language.

First, the usage of const:

1. Const read-only variable:

Variables modified by const are read-only and are essentially variables

Const-modified local variables allocate space on the stack

Const-decorated global variables allocate space in the global data area

Const is useful only at compile time, not at run time

Note: the variable modified by const is not a true constant, it just tells the compiler that the variable cannot appear to the left of the assignment symbol.

2. Divergence of const global variables:

In modern c language compilers, modifying const global variables will cause the program to crash

Standard c language compilers do not store const-decorated global variables in read-only storage, but in modifiable global data areas, whose values can still be changed

3. Code example:

(1) example of read-only variable code:

# include

Int main ()

{

Const int a = 10

Printf ("a =% d\ n", a)

Axi20

Printf ("a =% d\ n", a)

Return 0

}

Running result:

Test.c: In function 'main':

Test.c:8:4: error: assignment of read-only variable 'a'

Axi20

^

Note: it shows that this result is normal, the variable an is modified by const, and it becomes read-only.

(2) if the value of variable an is modified:

# include

Int main ()

{

Const int a = 10

Int * p = (int *) & a

Printf ("a =% d\ n", a)

* pendant 20

Printf ("a =% d\ n", a)

Return 0

}

Running result:

Root@txp-virtual-machine:/home/txp#. / a.out

A = 10

A = 20

Note: the value of a can be modified by pointer, which also demonstrates that the variable modified by const is read-only and essentially a variable.

(3) const modifies global variables:

Code version one

# include

Const int b = 40

Int main ()

{

Printf ("b =% d\ n", b)

Baked 20

Printf ("b =% d\ n", b)

Return 0

}

Output result:

Root@txp-virtual-machine:/home/txp# gcc test.c

Test.c: In function 'main':

Test.c:10:4: error: assignment of read-only variable 'b'

Baked 20

^

Note: the same as the use of variables on the const decoration stack

Code version two

# include

Const int b = 40

Int main ()

{

Int * p = (int *) & b

Printf ("b =% d\ n", b)

* pendant 20

Printf ("b =% d\ n", b)

Return 0

}

Running result:

Root@txp-virtual-machine:/home/txp#. / a.out

B = 40

Segmentation fault (core dumped)

Note: there is a segment error, which validates what we said above, "modifying the const global variable will cause the program to crash."

At the same time, in order to verify that the standard c language compiler will not store const-decorated global variables in read-only storage, but in modifiable global data areas, and their values can still be changed, I put this code to experiment on dev C++:

Description: my version of the compiler supports the standard c language, so it does not cause the program to crash and can run normally

4. The essence of const

Const in C language makes variables read-only.

Const in modern c compilers stores variables with global lifecycles in read-only storage, not in global data areas

Note: const cannot define a real constant; also note here that the variable modified by the static keyword has the same lifetime as a global variable.

Code example:

# include

Const int Array [5] = {0}

Void fun (int * pjinint v)

{

* pairv

}

Int main ()

{

Int const i = 1

Const static int j = 2

Int const array [5] = {0}

Fun ((int *) & iMagol 1)

Fun ((int *) & jMagol 2)

Fun ((int *) & array [2], 3)

Fun ((int *) & Array [1], 4)

Return 0

}

Output result:

Root@txp-virtual-machine:/home/txp#. / a.out

Segmentation fault (core dumped)

Note: there will be segment errors, which occur in const+static-decorated j variables to modify it, and const-decorated global arrays.

5. Const modifies function parameters and return values

The parameter of the const modified function indicates that you do not want to change the value of the parameter in the body of the function.

The return value of the const modifier function indicates that the return value is immutable, which is mostly used in the case of returning a pointer.

The literal amount of strings in the c language is stored in read-only storage, and const char* pointers are required in the program, for example:

Const char * s = "TXP embedded"; / / string literals

Code example:

# include

Const char*fun (const int i)

{

ITunes 8

Return "TXP"

}

Int main ()

{

Const char * p=fun (0)

Printf ("% s\ n", p)

P [1] ='_'

Printf ("% s\ n", p)

Return 0

}

Output result:

Root@txp-virtual-machine:/home/txp# gcc test.c

Test.c: In function 'fun':

Test.c:5:4: error: assignment of read-only parameter 'i'

ITunes 8

^

Test.c: In function 'main':

Test.c:12:5: error: assignment of read-only location'* (p + 1U)'

P [1] ='_'

^

Note: if it is written above, there must be a problem.

Code evolution:

# include

Const char*fun (const int i)

{

/ / iTun8

Return "TXP"

}

Int main ()

{

Const char * p=fun (0)

Printf ("% s\ n", p)

/ / p [1] ='_'

/ / printf ("% s\ n", p)

Return 0

}

Output result:

Root@txp-virtual-machine:/home/txp#. / a.out

TXP

II. The usage of volatile

To be honest, this keyword often appears in interview questions, but when you usually study, if you don't really understand the meaning, you may vaguely remember several conclusions in your head during the written exam, but sometimes, it's not impossible to forget the conclusion when you get nervous, so let's be honest and really understand its principle. If you come to the battlefield in this way, you will not be afraid, and you will write less bug in the future.

1. The common conclusions of volatile (the original meaning of volatile is changeable)

Here I will first give the conclusion, and then give an example, explain this example clearly, and all the conclusions will be clear.

Volatile can be understood as "compiler warning pointer"

Volatile tells the compiler that it must fetch the value of a variable from memory every time

Volatile mainly modifies variables that may be accessed by multiple threads

Volatile can also modify variables that may be changed by unknown factors.

Volatile can modify non-automatic variables that will be accessed in an interrupt subroutine.

2. Analysis principle

You may usually study in the blog, will find that explain the compiler optimization, and then add the volatile key to modify the variable, tell the compiler not to optimize this variable, so what does the optimization here mean?

Literally understand the word "optimization", which means the optimal value (the value of the variable does not change). Let me explain it with a simple code:

# include

Int main ()

{

Int a = 1 Splink volatile int a = 0

While (a)

{

}

}

Description: the above code, if the variable an is not modified by volatile, the compiler will optimize it (that is, the value of a remains the same), so while will always be a dead loop; then if I add volatile to modify, the compiler will not optimize variable a, which means that the value of variable a may change and while will not always loop.

Of course, in order to understand, what I said is not very professional, not from the register and memory point of view. (I don't want to explain it like that, just understand it.)

At this point, I believe you have a deeper understanding of "how to use const and volatile in C language". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report