c - 了解逗号运算符

标签 c comma-operator

int main()
{
    int a = (1,2,3);
    int b = (++a, ++a, ++a);
    int c= (b++, b++, b++);
    printf("%d %d %d", a,b,c);
}

我是编程初学者。我不明白这个程序如何显示 6 9 8 的输出。

最佳答案

三个声明中都使用了,

int a = (1,2,3);
int b = (++a, ++a, ++a);
int c = (b++, b++, b++);  

comma operator .它计算第一个操作数1 并将其丢弃,然后计算第二个操作数并返回其值。因此,

int a = ((1,2), 3);          // a is initialized with 3.
int b = ((++a, ++a), ++a);   // b is initialized with 4+1+1 = 6. 
                             // a is 6 by the end of the statement
int c = ((b++, b++), b++);   // c is initialized with 6+1+1 = 8
                             // b is 9 by the end of the statement.

1 在逗号运算符的情况下,保证从左到右计算顺序。

关于c - 了解逗号运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34154625/

相关文章:

c - 已删除共享内存但出现 shm ipc_id 错误

关闭 SSH 连接,同时更改 IP 地址

c - 需要帮助理解 C 中表达式的求值顺序

c - GCC 程序集输出 : Get variables declared 'extern'

c - 逗号运算符 , 有什么作用?

c++ - c++11 for 循环的逗号运算符

c - dlclose 加载了 RTLD_NODELETE 的库

javascript - 逗号运算符在 JavaScript 中有什么作用?

c++ - "cout << (a, b)"的输出是什么,为什么?

c - 请解释此程序中的逗号运算符