[英]What is the result of while(i=20) or any number in general in a C program?
Came across this question somewhere- 在某个地方遇到了这个问题-
What is the output of the following program 以下程序的输出是什么
int main(void) {
int i = 10 ;
while ( i = 20 )
printf ( "\nA computer buff!" ) ;
return 0;
}
Now I know that every non-zero number is treated as true in C but I haven't been able to figure out the result of using an assignment operator inside while. 现在我知道在C语言中每个非零数字都被视为true,但是我还无法弄清楚while内使用赋值运算符的结果。 When I run the code "A computer buff" got printed unknown number of times in a loop.
当我运行代码“计算机迷”时,循环中打印的次数未知。 I know it's a stupid question but question nonetheless.
我知道这是一个愚蠢的问题,但仍然存在疑问。
That should be an infinite loop, because i = 20
will yield 20 as a result of the assignment expression. 那应该是一个无限循环,因为赋值表达式的结果是
i = 20
将产生20。
An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand.
赋值操作将右操作数的值分配给左操作数命名的存储位置。 Therefore, the left-hand operand of an assignment operation must be a modifiable l-value.
因此,赋值操作的左侧操作数必须是可修改的l值。 After the assignment, an assignment expression has the value of the left operand but is not an l-value.
赋值后,赋值表达式具有左操作数的值,但不是l值。
In your code 在你的代码中
while ( i = 20 )
is essentially assigning 20 to i
and then taking the i
as the conditional check for while
loop. 本质上是为
i
分配20,然后将i
作为while
循环的条件检查。 As there in no break
ing condition inside the loop body, it is effectively an infinite loop. 由于循环体内没有
break
条件,因此实际上是无限循环。
You can easily check it on *nix by using the -S option in gcc. 您可以使用gcc中的-S选项在* nix上轻松检查它。 I took this file:
我拿了这个文件:
#include <stdio.h>
main( ){
int i = 10 ;
while ( i == 20 )
printf ( "\nA computer buff!" );
}
with gcc -S test.c
and it gave me out this assambly: 用
gcc -S test.c
,它给了我聪明的信息:
.file "c.c"
.section .rodata
.LC0:
.string "\nA computer buff!"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl $10, -4(%rbp)
nop
.L2:
movl $20, -4(%rbp)
movl $.LC0, %edi
movl $0, %eax
call printf
jmp .L2
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4"
.section .note.GNU-stack,"",@progbits
You can see at jmp .L2
that this is the only branch, responsible for the loop, which is uncondicional. 您可以在
jmp .L2
看到这是唯一负责循环的分支,这是非决定性的。 movl $20, -4(%rbp)
is the assignment of 20 to i. movl $20, -4(%rbp)
是i的赋值20。
while(1) is infinite loop so its execute number of time. while(1)是无限循环,因此其执行次数。 If you want to move out from the loop after the first iteration then use break statement in loop.
如果要在第一次迭代后从循环中移出,请在循环中使用break语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.