为什么在显示后者 'tot' 时不考虑复合赋值?

Why isn't the compound assignment taken into account when displaying the latter 'tot'?

#include <stdio.h>

main() {

    int pro;        
    int dot;        
    int tot;        
    char prelude[] = "\nNow we shall do some simple mathematics\n\n";

    printf("%s", prelude);

    pro = 3;        
    dot = 5;
    tot = pro + dot;        
    printf("%d", tot);        
    dot += 23;        
    printf("\n%d\n", tot);        
    return 0;
}

因为 C 不提供自动数据绑定。当您使用赋值运算符(或您的情况下的加法赋值)时,您正在为表达式右侧的语句分配 VALUE

variable = statement表示statement会计算出某个值,这个值会根据variable的数据类型赋值给variable

这意味着您正在为该变量分配一个值,而不是实际的语句

为了更好地解释它:

tot = pro + dot; 

执行以下操作:

  1. 我需要将我必须计算的东西分配给变量tot
  2. Something是一个语句,pro + dot.
  3. 这个语句是一个加法,一个需要两个操作数的运算。
  4. 操作数 1 是 pro,它的计算结果为 3。(意味着 C 将替换 pro with 3 in the statement)
  5. 操作数 2 是 dot,计算结果为 5。
  6. 计算所有操作数。
  7. 语句为:3 + 5;
  8. 计算结果为 8,一个整数。
  9. 表达式变成了tot = 8;
  10. 将值 8 分配给 tot。这意味着,转到内存地址 tot所代表的变量,写入整数8(在 符合 C standard/machine 架构)。

如果你这样做

dot += 23;

C 理解这一点:

dot += 23; //  can be translated to `dot = dot + 23;'

像以前一样:

  1. dot表示8,23表示23。
  2. 语句:8 + 23
  3. 语句的计算结果为 31。dot = 31;,意思是写 整数 31 到 dot.
  4. 的内存

现在 tot 不受此影响。为什么?因为 tot 在你的记忆中是一个 space,它的值为 8。它不知道 8 是通过添加 2 个其他变量创建的。只有8个。所以改变其他变量,不会影响这个。

如果您这样做 dot += 23;,您正在更改变量 dot 的内存,而不是 tot 的内存。

您所期望的称为数据绑定,它是比 C 提供的更高级别的功能。