当前位置:网站首页>The macro definition of embedded C language development and the skills of finding the maximum value of two numbers
The macro definition of embedded C language development and the skills of finding the maximum value of two numbers
2022-07-25 06:03:00 【Do you want to buy vegetables!】
The embedded c Macro definition of language development tips for finding the maximum value of two numbers
One 、 Go back and wait for the notice
1、#define MAX(x,y) x > y ? x : y
Vulnerability resolution :
#define MAX(x,y) x > y ? x : y
int main(void)
{
printf("max=%d",MAX(1,2));
printf("max=%d",MAX(1!=1,1!=2));
return 0;
}
Test section 2 Line statement
printf("max=%d",1!=1>1!=2?1!=1:1!=2)
When the macro parameter is an expression , It is found that the actual operation result is max=0, As we expected max=1 Dissimilarity . Because the comparison operator > The priority of 6, Greater than !=( The priority for 7), So the expanded expression , The order of operations has changed , The result is not what we expected .
Two 、 Talk more 10 The writing method of minutes
2.1、#define MAX(x,y) (x) > (y) ? (x) : (y)
Vulnerability resolution :
#define MAX(x,y) (x) > (y) ? (x) : (y)
int main(void)
{
printf("max=%d",3 + MAX(1,2));
return 0;
}
In the program , We print expressions 3 + MAX(1, 2) Value , The expected result should be 5, But the actual operation result is 1. When we unfold , Found the same problem :
3 + (1) > (2) ? (1) : (2);
Because operators + Has a higher priority than the comparison operator >, So the expression becomes 4>2?1:2, The final result is 1 No wonder .
3、 ... and 、 How to write the next round of interview
Continue to modify this macro :
3.1、#define MAX(x,y) ((x) > (y) ? (x) : (y))
Use parentheses to wrap macro definitions , This avoids when an expression contains both macro definitions and other high priority operators , Destroy the operation order of the whole expression . If you can write about this step , That means you are better than the one who passed the interview , The former student has gone back to wait for news , We go on to the next round of interviews .
Four 、 to offer Writing
4.1、
#define MAX(x,y)({ \
int _x = x; \
int _y = y; \
_x > _y ? _x : _y;\
})
above #define MAX(x,y) ((x) > (y) ? (x) : (y)), Although it solves the problem caused by operator priority , But there are still some loopholes . such as , We use the following test program to test our defined macro :
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
int i = 2;
int j = 6;
printf("max=%d",MAX(i++,j++));
return 0;
}
In the program , We define two variables i and j, Then compare the size of the two variables , And do auto increment operation . The actual operation results show that max = 7, Rather than the expected outcome max = 6. This is because of variables i and j After the macro is expanded , I did two auto increment operations , Cause to print out i The value of is 7. In this case , So what should we do ? Now , It's time for statement expressions to come into play . We can use statement expressions to define this macro , Define two temporary variables in the statement expression , Separately for temporary storage i and j Value , And then compare them , In this way, we can avoid two self accretion 、 Self reduction problem .
#define MAX(x,y)({
\ int _x = x; \ int _y = y; \ _x > _y ? _x : _y; \ })
int main(void)
{
int i = 2;
int j = 6;
printf("max=%d",MAX(i++,j++));
return 0;
}
In a statement expression , We defined 2 Local variables _x 、 _y To store macro parameters x and y Value , And then use _x and _y To compare the size , This avoids i and j It brings 2 The problem of subautonomy operation .
5、 ... and 、 Can talk about the way of treatment
5.1
#define MAX(type,x,y)({ \
type _x = x; \
type _y = y; \
_x > _y ? _x : _y; \
})
on top 4.1 In this macro , The two temporary variable data types we define are int type , Only two integers can be compared . So for other types of data , You need to redefine a macro , It's too much trouble ! We can continue to modify based on the above macro , Let it support any type of data comparison size :
#define MAX(type,x,y)({
\ type _x = x; \ type _y = y; \ _x > _y ? _x : _y; \ })
int main(void)
{
int i = 2;
int j = 6;
printf("max=%d\n",MAX(int,i++,j++));
printf("max=%f\n",MAX(float,3.14,3.15));
return 0;
}
In this 5.1 In macro , Let's add a parameter :type, Used to specify temporary variables _x and _y The type of . such , We're comparing the size of two numbers , As long as 2 The type of data is passed to the macro as an argument , You can compare any type of data . If you can be in an interview , Write a macro like this , The interviewer will be very happy , He usually tells you : wait a moment , wait for a meeting with sb. HR I'll talk to you about the treatment .
6、 ... and 、 Pay a high salary
6.1、
#define max(x, y) ({ \
typeof(x) _x = (x); \
typeof(y) _y = (y); \
(void) (&_x == &_y);\
_x > _y ? _x : _y; })
above 5.1 In the macro definition of , We added a type Type parameter , To be compatible with different data types , At the moment , For salary , We should also omit this . How to do ? Use typeof That's all right. ,typeof yes GNU C A new keyword , To get the data type , We don't have to pass in the reference , Give Way typeof Direct access to !
#define max(x, y) ({
\ typeof(x) _x = (x); \ typeof(y) _y = (y); \ (void) (&_x == &_y);\ _x > _y ? _x : _y; })
In this macro definition , Used typeof Keyword is used to get the two parameter types of a macro . Dry goods in (void) (&x == &y); this sentence , It's a genius design !
1、 It is mainly used to detect the two parameters of macros x and y Whether or not the data type of . If it's not the same , compile
The alarm will send a warning message , Program developers remind .
2、 When two values are compared , The results of the comparison are not used , Some compilers may give a warning, Add one (void) after , You can eliminate this warning !
At the moment , The interviewer sees your macro , I guess I'll take a breath back , This guy is better than me !
6、 ... and 、 stay Linux Writing in the kernel
/kernel/include/linux/kernel.h
/* * min()/max()/clamp() macros that also do * strict type-checking.. See the * "unnecessary" pointer comparison. */
#define min(x, y) ({
\ typeof(x) _min1 = (x); \ typeof(y) _min2 = (y); \ (void) (&_min1 == &_min2); \ _min1 < _min2 ? _min1 : _min2; })
#define max(x, y) ({
\ typeof(x) _max1 = (x); \ typeof(y) _max2 = (y); \ (void) (&_max1 == &_max2); \ _max1 > _max2 ? _max1 : _max2; })
#define min3(x, y, z) min((typeof(x))min(x, y), z)
#define max3(x, y, z) max((typeof(x))max(x, y), z)
After watching the implementation of this macro , We have to lament the breadth and profundity of the kernel ! Every detail , Every careless sentence , Fine products , Can learn a lot of knowledge , Let your C Language skills are more profound .
summary
This article is from 《 The embedded C Language self-cultivation 》 My summary and share !
边栏推荐
- Concepts of phase velocity and phase in transmission line theory
- 基于ISO13209(OTX)实现EOL下线序列
- HTB-Beep
- Unity Animator动画与状态机
- Leetcode/ binary addition
- Singing "Seven Mile fragrance" askew -- pay tribute to Jay
- For data security reasons, the Dutch Ministry of Education asked schools to suspend the use of Chrome browser
- Leetcode 237. delete nodes in the linked list
- (16)[系统调用]追踪系统调用(3环)
- HTB-Devel
猜你喜欢
![[ultra detailed diagram] FPN + mask RCNN](/img/ef/ddd62fe7e54074c134aa5ee4cc5840.png)
[ultra detailed diagram] FPN + mask RCNN

(2022牛客多校二)K-Link with Bracket Sequence I(动态规划)

Concepts of phase velocity and phase in transmission line theory

Big talk · book sharing | Haas Internet of things device cloud integrated development framework

Linear algebra (3)

Please stop using system The currenttimemillis() statistical code is time-consuming, which is really too low!

【每日一练】day(14)
![Get URL of [url reference]? For the following parameters, there are two ways to get the value of the corresponding parameter name and convert the full quantity to the object structure](/img/78/2a4e9d49bee8ef839d9d86fc7c3c83.png)
Get URL of [url reference]? For the following parameters, there are two ways to get the value of the corresponding parameter name and convert the full quantity to the object structure

New developments in Data Governance: what is the impact of the EU's Data Governance Research Report on China

npx和npm区别
随机推荐
HTB-Granpa
2021 ICPC Shaanxi warm up match b.code (bit operation)
新时代生产力工具——FlowUs 息流全方位评测
Mechanism and principle of multihead attention and masked attention
What projects can make money online? Is it reliable to be we media?
Big talk · book sharing | Haas Internet of things device cloud integrated development framework
Siggraph 2022 -- rendering iridescent rock dove neck feathers
context must be a dict rather解决
R language uses data.table function to create data.table data (use: operator to create continuous numeric vector)
Unity Animator动画与状态机
Detailed explanation of stepn chain game system development mode (Sports money making mode)
Codeforces Round #809 (Div. 2)
G1 garbage collector
Android interview question: why do activities rebuild ViewModel and still exist—— Jetpack series (3)
node.express中req.body总是undefind解决
Run length test of R language: use the runs.test function to perform run length test on binary sequence data (check whether the sequence is random)
New discovery of ROS callback function
sqlilabs less-29
[QT] solve the problem of Chinese garbled code output from QT console
[daily practice] day (14)