c++ - while 循环有两个参数吗?

标签 c++ c while-loop g++

我的女士给了我一个问题要解决。预测以下代码的输出。

#include <stdio.h>
int main()
{
    int i = 0, j = 0;
    printf("Output is : ");
    while (i < 5, j < 10)    // Doubt: how does while accept 2 arguments?? and how it works??
    {
        i++;
        j++;
    }
    printf("%d, %d\n", i, j);
}

我以为是语法错误。但是当我尝试运行时,它给了我输出。

Output is : 10, 10

但是怎么办?谁能解释一下?

但是,如果我删除第一个 printf 语句 printf("Output is : "); 并运行它,我的防病毒软件会发出警报,提示我检测到 Trojan。 但是它是如何变成木马的呢?

最佳答案

comma operator是一个二元运算符,它计算第一个操作数并丢弃结果,然后计算第二个操作数并返回该值。

所以在你的情况下,

First it will increment i and j upto 5 and discard.
Second it will iterate i and i upto 10 and provide you the result as 10, 10.

您可以使用以下代码确认,

while (i < 5, j < 10)    // Doubt: how does while accept 2 arguments?? and how it works??
{
    i++;
    j+ = 2;
}

关于c++ - while 循环有两个参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27133845/

相关文章:

c++ - 移除 QJsonArray 中的所有元素

c - pthreads,我怎么知道进程内的另一个线程没有在等待?

java - while 循环设置为 false 后不再重复

c++ - 带私有(private)构造函数的 vector <class>

c++ - Qt:在QNetworkAccessManager中发送请求后连接信号

c - MIPS64 汇编中的 double 值数组

c - C 中具有函数的枚举

使用随机数的javascript彩票游戏我的逻辑有什么问题

c - 如何理解带有指针的字符串

c++ - 排序后的数据插入unordered_map