当前位置:网站首页>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 !
边栏推荐
- HTB-Optimum
- 2021 ICPC Shaanxi warm up match b.code (bit operation)
- ABC 261.D - Flipping and Bonus ( DP )
- R language Visual scatter diagram, geom using ggrep package_ text_ The repl function avoids overlapping labels between data points (set the hJust parameter to show that labels of all data points are a
- Unity Animator动画与状态机
- (Niuke multi School II) j-link with arithmetic progress (least square method / three points)
- 剑指 Offer 54. 二叉搜索树的第k大节点
- ROI pooling and ROI align
- 2020ICPC 江西省赛热身赛 E.Robot Sends Red Packets(dfs)
- G1 garbage collector
猜你喜欢

(牛客多校二)G-Link with Monotonic Subsequence(构造题)

HTB-Granpa

VO, dto, do, Po distinction and use

(Niuke multi school I in 2022) i-chiitoitsu (expected DP)

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

node.express中req.body总是undefind解决

The computer accesses the Internet normally with the same network cable, and the mobile phone connects to WiFi successfully, but it cannot access the Internet

Amazoncaptcha bypasses Amazon IP verification code with 95% success rate

Sword finger offer 54. the k-th node of the binary search tree

(Niuke multi School II) G-LINK with monotonic subsequence (construction question)
随机推荐
Summer summary 2
HTB-Optimum
剑指 Offer 36. 二叉搜索树与双向链表
Calculate BDP value and wnd value
Differences and application directions of GPS, base station and IP positioning
剑指 Offer 54. 二叉搜索树的第k大节点
Leetcode 204. count prime numbers (wonderful)
This is how the permission system is designed, yyds
[ultra detailed diagram] FPN + mask RCNN
Talk about how redis handles requests
有什么能在网上挣钱的项目啊?做自媒体靠谱吗?
The u-collapse component of uniapp mobile uview is highly init
剑指 Offer 45. 把数组排成最小的数
Brief introduction of acoustic filter Market
JS how to delete an element without deleting its child elements
[node] the service port is occupied error: listen eaddinuse: address already in use::: 9000- how to close the port started by node
10. Rendering Basics
Android interview question: why do activities rebuild ViewModel and still exist—— Jetpack series (3)
Dynamic planning learning notes
Adaptation dynamics | in June, sequoiadb completed mutual certification with five products