c++ - 程序输出(C++ 的基本运算符)。操作顺序?

标签 c++ operator-keyword

// H2.cpp : Tihs program runs different mathmatical operations on numbers given by the user

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int a;
    cout << "Enter a number for a: "; //Prompts the user for a and b inputs
    cin >> a;

    int b;
    cout << "Enter a number for b: ";
    cin >> b;

    cout << "A is " << a << "\tB is " << b << endl;
    cout <<"Sum of a and b is equal to " << a << " + " << b << " and the result is " << (a + b) << endl; //Performs addition operator and gives output
    cout <<"Product of a and b is equal to " << a << " * " << b << " and the result is " << (a * b) << endl;
    cout <<"a > b is " << a << " > " << b << " and the result is " << (a > b) << endl;
    cout <<"a < b is " << a << " > " << b << " and the result is " << (a < b) << endl;
    cout <<"a == b is " << a << " == " << b << " and the result is " << (a == b) << endl; //Performs boolean operator and outputs result
    cout <<"a >= b is " << a << " >= " << b << " and the result is " << (a >= b) << endl;
    cout <<"a <= b is " << a << " <= " << b << " and the result is " << (a <= b) << endl;
    cout <<"a != b is " << a << " != " << b << " and the result is " << (a != b) << endl;
    cout <<"a -= b is " << a << " -= " << b << " and the result is a = " << (a -= b) << endl; //Performs - operator on a - b and makes a equal to the new result
    cout <<"a /= b is " << a << " /= " << b << " and the result is a = " << (a /= b) << endl;
    cout <<"a %= b is " << a << " %= " << b << " and the result is a = " << (a %= b) << endl; //Performs % operator on a % b and makes a equal to the new result. Ripple effect created from previous 2 lines as the value of a changes each time.

return 0;

我关心的输出在这里:

a -= b is -4198672 -= 4198672 and the result is a = -4198672
a /= b is -1 /= 4198672 and the result is a = -1
a %= b is -1 %= 4198672 and the result is a = -1

显示的a的值好像是这行代码执行后a的值。我确定这与操作顺序有关,但我不确定如何解决这个问题。非常感谢任何帮助。

最佳答案

计算运算符或函数的参数的顺序在 C++ 中未定义。如果不同参数的评估有副作用,只要编译器认为合适,这些就会发生,如果对同一对象进行多次修改,结果是未定义的行为。如果你想强制一个特定的评估顺序,你需要将你的表达式分解成多个单独的表达式,因为它们是按顺序评估的,或者你可以注入(inject)创建序列点的运算符。但是,创建序列点的运算符不能很好地与链接输出运算符配合使用。强制在其他参数之前评估第一个参数的运算符列表是:

  • 运营商
  • 逻辑 && 和 ||运营商
  • 条件运算符 ?:

当然,如果您重载这些运算符中的任何一个,它们将停止引入序列点,因为它们变成了正常的函数调用。

关于c++ - 程序输出(C++ 的基本运算符)。操作顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18907083/

相关文章:

c++ - 为什么在 __assume 中使用函数调用时 MSVC 不报错?

c++ - 如何修改给定的类以使用 const 运算符

Ruby:仅在某些情况下重载运算符行为

c++ - 在 MacOSX 上的 Qt 5.1 中,大小控制从状态栏中消失了

c++ - 部分易失变量?

c++ - 显示包含 header 后生成的 c/c++ 文件(在翻译为机器语言之前)

c++ - 使用基类的运算符>>创建派生类

c++ - "class has no constructors"类模板错误

C++抛出异常非法

C++赋值运算符重载