编程介的小学生 2019-12-03 00:15 采纳率: 20.5%
浏览 79

#define is unsafe 定义的问题

Problem Description
Have you used #define in C/C++ code like the code below?

#include
#define MAX(a , b) ((a) > (b) ? (a) : (b))
int main()
{
printf("%d\n" , MAX(2 + 3 , 4));
return 0;
}

Run the code and get an output: 5, right?
You may think it is equal to this code:

#include
int max(a , b) { return ((a) > (b) ? (a) : (b)); }
int main()
{
printf("%d\n" , max(2 + 3 , 4));
return 0;
}

But they aren't.Though they do produce the same anwser , they work in two different ways.
The first code, just replace the MAX(2 + 3 , 4) with ((2 + 3) > (4) ? (2 + 3) : 4), which calculates (2 + 3) twice.
While the second calculates (2 + 3) first, and send the value (5 , 4) to function max(a , b) , which calculates (2 + 3) only once.

What about MAX( MAX(1+2,2) , 3 ) ?
Remember "replace".
First replace: MAX( (1 + 2) > 2 ? (1 + 2) : 2 , 3)
Second replace: ( ( ( 1 + 2 ) > 2 ? ( 1 + 2 ) : 2 ) > 3 ? ( ( 1 + 2 ) > 2 ? ( 1 + 2 ) : 2 ) : 3).
The code may calculate the same expression many times like ( 1 + 2 ) above.
So #define isn't good.In this problem,I'll give you some strings, tell me the result and how many additions(加法) are computed.

Input
The first line is an integer T(T<=40) indicating case number.
The next T lines each has a string(no longer than 1000), with MAX(a,b), digits, '+' only(Yes, there're no other characters).
In MAX(a,b), a and b may be a string with MAX(c,d), digits, '+'.See the sample and things will be clearer.

Output
For each case, output two integers in a line separated by a single space.Integers in output won't exceed 1000000.

Sample Input
6
MAX(1,0)
1+MAX(1,0)
MAX(2+1,3)
MAX(4,2+2)
MAX(1+1,2)+MAX(2,3)
MAX(MAX(1+2,3),MAX(4+5+6,MAX(7+8,9)))+MAX(10,MAX(MAX(11,12),13))

Sample Output
1 0
2 1
3 1
4 2
5 2
28 14

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#python#的问题:求帮写python代码
    • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?