对整数变量 n c 的逗号分隔赋值

标签 c variable-assignment comma-operator

我无法理解这段代码的工作原理。

#include<stdio.h>
void main(){
  int a,b;
  a=3,1;
  b=(5,4);
  printf("%d",a+b);
}  

输出为7 。该任务是什么?

最佳答案

逗号运算符计算其第一个操作数并丢弃结果,然后计算第二个操作数并返回该值。

执行后

a=3,1;  //  (a = 3), 1;

a 将包含 3 及之后的

b=(5,4);  // Discard 5 and the value of the expression (5,4) will be 4

b 将有 4

关于 Wikipedia 的更多示例:

// Examples:               Descriptions:                                                                   Values after line is evaluated:
int a=1, b=2, c=3, i=0; // commas act as separators in this line, not as an  operator 
                        // ... a=1, b=2, c=3, i=0
i = (a, b);             // stores b into i 
                        // ... a=1, b=2, c=3, i=2
i = a, b;               // stores a into i. Equivalent to (i = a), b;
                        // ... a=1, b=2, c=3, i=1
i = (a += 2, a + b);    // increases a by 2, then stores a+b = 3+2 into i
                        // ... a=3, b=2, c=3, i=5
i = a += 2, a + b;      // increases a by 2, then stores a to i, and discards unused
                        // a + b rvalue. Equivalent to (i = (a += 2)), a + b; 
                        // ... a=5, b=2, c=3, i=5
i = a, b, c;            // stores a into i, discarding the unused b and c rvalues
                        // ... a=5, b=2, c=3, i=5
i = (a, b, c);          // stores c into i, discarding the unused a and b rvalues
                        // ... a=5, b=2, c=3, i=3
return a=4, b=5, c=6;   // returns 6, not 4, since comma operator sequence points
                        // following the keyword 'return' are considered a single
                        // expression evaluating to rvalue of final   subexpression c=6
return 1, 2, 3;         // returns 3, not 1, for same reason as previous example
return(1), 2, 3;        // returns 3, not 1, still for same reason as above.  This
                        // example works as it does because return is a keyword, not 
                        // a function call. Even though most compilers will allow for
                        // the construct return(value), the parentheses are syntactic
                        // sugar that get stripped out without syntactic analysis 

关于对整数变量 n c 的逗号分隔赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29218727/

相关文章:

Python:避免if条件?

使用 4 维数组的 Java 程序

c++ - 逗号运算符如何工作

python - 用 C 解释来自 Modbus ASCII 的数据

c - 在 Lua 之外使用 Lua 的哈希表是否可能/实用?

c - 通过 scanf 定义列表的大小

c - 当 for 循环的条件部分有多个用逗号分隔的表达式时会发生什么?

c - 如何正确地将指针传递给指针数组?

函数内部的javascript变量指针

c++ - 逗号运算符的局限性