Shr*_*yak 3 c c++ g++ while-loop
我的女士给了我一个问题要解决。预测以下代码的输出。
#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);
}
Run Code Online (Sandbox Code Playgroud)
我以为是语法错误。但是当我尝试运行时,它给了我输出。
Output is : 10, 10
Run Code Online (Sandbox Code Playgroud)
但是如何?谁能解释一下?
但是如果我删除第一个 printf 语句printf("Output is : ");并运行它,我的防病毒软件会给我一个Trojan检测到a 的警报。但是它怎么变成了Trojan?
的逗号操作者是一个二进制运算符,并将其评估其第一操作数和丢弃结果,然后计算第二个操作数并返回该值。
所以在你的情况下,
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.
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码进行确认,
while (i < 5, j < 10) // Doubt: how does while accept 2 arguments?? and how it works??
{
i++;
j+ = 2;
}
Run Code Online (Sandbox Code Playgroud)