c++ - C++中的复合赋值

标签 c++ assignment-operator compound-assignment

我想知道C++中复合赋值的执行流程。我遇到了一个 CodeChef question ,我在这里计算 NCR mod p 值并将它们加在一起得到最终答案:

// correct
for(int i=min1; i<=max1; i+=2){
     ans = (ans+ncr_mod_p(n,i))%mod;
}
// incorrect
for(int i=min1; i<=max1; i+=2){
     ans+=ncr_mod_p(n,i)%mod;
}
这是由于整数溢出而发生的。
那么,复合赋值的执行顺序是怎样的呢?
假设我们有一个方程 a+=b%c那么执行顺序是什么:
a = (a+b)%c
// OR
a = a+(b)%c;

最佳答案

这个说法

ans+=ncr_mod_p(n,i)%mod;
相当于声明
ans = ans + ( ncr_mod_p(n,i)%mod );
如您所见,它与声明不同
ans = (ans+ncr_mod_p(n,i))%mod;
来自 C++ 14 标准(5.18 赋值和复合赋值运算符)

7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.

关于c++ - C++中的复合赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65811703/

相关文章:

c++ - 当我对具有复制构造函数但没有赋值运算符的对象进行赋值时会发生什么?

c - += 和 =+ C 赋值运算符有什么区别

c++ - 'malloc_stats' 函数中的奇怪行为

c++ - QWidget和QMessageBox的显示

c++ - 为什么我的指针输出一个字符串而不是 C++ 中的内存地址?

java - 为什么在java中不允许没有括号的赋值和 boolean 运算符

c++ - _T( ) 宏更改为 UNICODE 字符数据

c++ - 没有 return 语句的重载赋值运算符

java - 为什么 Java 没有条件与和条件或运算符的复合赋值版本? (&&=, ||=)

javascript - 复合let/const 赋值是什么意思?