zoukankan      html  css  js  c++  java
  • 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,说明此段代码依赖编译器,是未定义的代码
    错误原因: C语言对表达式的求值顺序不是明确规定的,而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;
    	}
    }
  • 相关阅读:
    JSP内置对象
    Angular $scope和$rootScope事件机制之$emit、$broadcast和$on
    Ionic开发实战
    Entity Framework 5.0 Code First全面学习
    6个强大的AngularJS扩展应用
    使用npm安装一些包失败了的看过来(npm国内镜像介绍)
    自己家里搭建NAS服务器有什么好方案?
    自己动手制作CSharp编译器
    使用Visual Studio Code搭建TypeScript开发环境
    Office web app server2013详细的安装和部署
  • 原文地址:https://www.cnblogs.com/xuesu/p/4296971.html
Copyright © 2011-2022 走看看