[英]What is the result of while(i=20) or any number in general in a C program?
在某個地方遇到了這個問題-
以下程序的輸出是什么
int main(void) {
int i = 10 ;
while ( i = 20 )
printf ( "\nA computer buff!" ) ;
return 0;
}
現在我知道在C語言中每個非零數字都被視為true,但是我還無法弄清楚while內使用賦值運算符的結果。 當我運行代碼“計算機迷”時,循環中打印的次數未知。 我知道這是一個愚蠢的問題,但仍然存在疑問。
那應該是一個無限循環,因為賦值表達式的結果是i = 20
將產生20。
來自文檔
賦值操作將右操作數的值分配給左操作數命名的存儲位置。 因此,賦值操作的左側操作數必須是可修改的l值。 賦值后,賦值表達式具有左操作數的值,但不是l值。
在你的代碼中
while ( i = 20 )
本質上是為i
分配20,然后將i
作為while
循環的條件檢查。 由於循環體內沒有break
條件,因此實際上是無限循環。
您可以使用gcc中的-S選項在* nix上輕松檢查它。 我拿了這個文件:
#include <stdio.h>
main( ){
int i = 10 ;
while ( i == 20 )
printf ( "\nA computer buff!" );
}
用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
您可以在jmp .L2
看到這是唯一負責循環的分支,這是非決定性的。 movl $20, -4(%rbp)
是i的賦值20。
while(1)是無限循環,因此其執行次數。 如果要在第一次迭代后從循環中移出,請在循環中使用break語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.