摘要:本文主要向大家介绍了C/C++知识点之C语言对表达式的求值顺序不是明确规定的,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了C/C++知识点之C语言对表达式的求值顺序不是明确规定的,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
讨论区看到的WA来自那些递归下降求解的代码.
第一种情况,使用|| 和 &&:
例如s为所给串
int getval()
{
switch(s[c_s++])
{
case ‘p‘: return (value & (1 << 0))? 1:0;
case ‘q‘: return (value & (1 << 1))? 1:0;
case ‘r‘: return (value & (1 << 2))? 1:0;
case ‘s‘: return (value & (1 << 3))? 1:0;
case ‘t‘: return (value & (1 << 4))? 1:0;
case ‘K‘: return getval() && getval();
case ‘A‘: return getval() || getval();
case ‘N‘: return !getval();
case ‘C‘: return !getval() || getval();
case ‘E‘: return getval() == getval();
}
}
这种情况简单,大家知道短路求值吧,先对 ||左边的表达式求值,如果非0,则不会对右边的表达式求值,&&同理,如果左边为0,不会对右边求值,这样下标就不会按照事先设想的增加
第二种情况,使用&和|:
int getval()
{
switch(s[c_s++])
{
case ‘p‘: return (value & (1 << 0))? 1:0;
case ‘q‘: return (value & (1 << 1))? 1:0;
case ‘r‘: return (value & (1 << 2))? 1:0;
case ‘s‘: return (value & (1 << 3))? 1:0;
case ‘t‘: return (value & (1 << 4))? 1:0;
case ‘K‘: return getval() & getval();
case ‘A‘: return getval() | getval();
case ‘N‘: return !getval();
case ‘C‘: return !getval() | getval();
case ‘E‘: return getval() == getval();
}
}
首先这段代码用G++会AC,C++会WA,说明此段代码依赖编译器,是未定义的代码
错误原因: ,而G++是从左从左向右求值,C++则正好相反,比如: getval() | getval() G++先对左边的getval()求值,而C++则先对右边的getval()求值,也就会导致对s的访问顺序不会按预先的步骤进行,所以用G++会ac,C++会WA掉
正确的写法,去掉那些跟依赖求值顺序的代码(好习惯),分别求值,用两个临时变量保存,这样G++和C++都AC了:
int getval()
{ int temp1, temp2;
switch(s[c_s++])
{
case ‘p‘: return (value & (1 << 0))? 1:0;
case ‘q‘: return (value & (1 << 1))? 1:0;
case ‘r‘: return (value & (1 << 2))? 1:0;
case ‘s‘: return (value & (1 << 3))? 1:0;
case ‘t‘: return (value & (1 << 4))? 1:0;
case ‘K‘: temp1 = getval(); temp2 = getval(); return temp1 & temp2;
case ‘A‘: temp1 = getval(); temp2 = getval(); return temp1 | temp2;
case ‘N‘: return !getval();
case ‘C‘: temp1 = !getval(); temp2 = getval(); return temp1 | temp2;
case ‘E‘: temp1 = getval(); temp2 = getval(); return temp1 == temp2;
}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号