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. 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.
From the docs
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. After the assignment, an assignment expression has the value of the left operand but is not an l-value.
In your code
while ( i = 20 )
is essentially assigning 20 to i
and then taking the i
as the conditional check for while
loop. As there in no break
ing condition inside the loop body, it is effectively an infinite loop.
You can easily check it on *nix by using the -S option in gcc. 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:
.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. movl $20, -4(%rbp)
is the assignment of 20 to i.
while(1) is infinite loop so its execute number of time. If you want to move out from the loop after the first iteration then use break statement in loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.