代码之家  ›  专栏  ›  技术社区  ›  Jason R. Mick

C++中同时赋值和条件测试

  •  2
  • Jason R. Mick  · 技术社区  · 14 年前

    我有三个返回整数错误码的函数,例如。

    int my_function_1(const int my_int_param);
    int my_function_2(const int my_int_param);
    int my_function_3(const int my_int_param);
    

    为了简洁起见,我想同时分配和测试错误。下列设备是否可以工作,是否可以携带?

    int error=0;
    ...
    if ( error ||
         (error = my_function_1(val1) ||
          error = my_function_2(val2) ||
          error = my_function_3(val3)) ) {
       std::cout << "AN ERROR OCCURRED!!!" << std::endl;
    }
    

    4 回复  |  直到 14 年前
        1
  •  4
  •   Puppy    14 年前

    为什么不抛出一个异常呢?

    void my_function_1(const int my_int_param);
    void my_function_2(const int my_int_param);
    void my_function_3(const int my_int_param);
    
    try {
        my_function_1(...);
        my_function_2(...);
        my_function_3(...);
    } catch(std::exception& e) {
        std::cout << "An error occurred! It is " << e.what() << "\n";
    }
    
        2
  •  2
  •   Mark Ransom    14 年前

    我不明白你为什么要 error && || 操作人员得到标准的保证。不过,我认为这是一种糟糕的风格。

    根据您的意见,您需要替换 错误(&A); error || . 我还要补充一点,这是使用异常而不是错误代码的一个很好的理由,它使您的代码更易于阅读。

        3
  •  0
  •   Naveen    14 年前

    error 初始化为 0 所以 && false . 所以世界的其他部分 if 条件永远不会被评估。所以这个代码不起作用。如果你移除 && 条件代码应该可移植,因为标准保证了这种情况下的求值顺序。

        4
  •  0
  •   kriss    14 年前

    && 具有 || =

    exception 行另一个海报建议,或简单地把您的检查代码内的功能,并做如下。

    int checked(){
        int error = 0;
        error = my_function_1(val1); if (error) return error;
        error = my_function_2(val1); if (error) return error;
        error = my_function_3(val1); if (error) return error;
        return error;
    }
    

    我相信任何程序员都很容易理解这里所做的事情。