簡體   English   中英

為什么下面的代碼僅對a = 1返回true?

[英]Why does the code below return true only for a = 1?

為什么下面的代碼僅對a = 1返回true?

main(){
int a = 10;
if (true == a)
     cout<<"Why am I not getting executed";
}

當Bool true轉換為int時,始終將其轉換為1。因此,您的代碼等效於:

main(){
   int a = 10;
   if (1 == a)
      cout<<"y i am not getting executed";
   }

這是C ++標准的一部分,因此您希望每一個符合C ++標准的編譯器都可以實現這一點。

您的打印語句未執行的原因是因為布爾值被隱式轉換為數字,而不是相反。 即您的if語句與此等效:if(1 == a)

您可以通過首先將其顯式轉換為布爾值來解決此問題:

main(){
int a = 10;
if (((bool)a) == true)
     cout<<"I am definitely getting executed";
}

在C / C ++中,false表示為0。

其他所有內容均表示為非零。 有時是1,有時是其他任何東西。 因此,您永遠不要測試是否等於真(==)。

相反,您應該測試是否存在錯誤。 由於false只有1個有效值。

在這里,我們正在測試所有非假值,它們中的任何一個都可以:

main(){
int a = 10;
if (a)
     cout<<"I am definitely getting executed";
}

第三個例子只是為了證明比較認為是假的整數與假(只有0)是安全的:

main(){
int a = 0;
if (0 == false)
     cout<<"I am definitely getting executed";
}

您的布爾值將提升為整數,然后變為1。

在C和C ++中,0為false,除0外為true:

if ( 0 )
{
// never run
}

if ( 1 )
{
// always run
}

if ( var1 == 1 )
{
// run when var1 is "1"
}

當編譯器計算布爾表達式時,它必須產生0或1。此外,還有一些方便的typedef和定義,它們使您可以在表達式中使用“ true”和“ false”而不是1和0。

因此,您的代碼實際上如下所示:

main(){
int a = 10;
if (1 == a)
     cout<<"y i am not getting executed";
}

您可能想要:

main(){
int a = 10;
if (true == (bool)a)
     cout<<"if you want to explicitly use true/false";
}

或實際上只是:

main(){
int a = 10;
if ( a )
     cout<<"usual C++ style";
}

因為true為1。如果要測試a的非零值,只需編寫if(a)。

我建議您切換到一個警告您此事的編譯器...(VC ++會產生以下警告:C4806警告:'==':不安全的操作:'bool'類型的值不能提升為'int'類型的值;我手頭沒有其他編譯器。)

我同意Lou Franco的觀點-您想知道變量是否大於零(或不等於零),對此進行測試。

如果您不了解最后一個細節,則編譯器隱式完成的所有操作都是危險的。

這是大多數人編寫這種代碼的方式:

main(){
int a = 10;
if (a) // all non-zero satisfy 'truth'
     cout<<"y i am not getting executed";
}

我也看到了:

main(){
int a = 10;
if (!!a == true) // ! result is guaranteed to be == true or == false
     cout<<"y i am not getting executed";
}

我不希望代碼被定義,並且您不應該依賴於編譯器給您的任何行為。 可能將true轉換為int(1),而沒有將a轉換為您期望的bool(true)。 最好寫出您的意思(a = 0),然后再依賴它(即使事實證明它已定義)。

不同於0(為假)的東西不一定為真(即1)

因為布爾值在C / C ++中有點,並且true表示為1,false表示為0。

更新:如評論中所述,我原來的答案是錯誤的。 所以繞開它。

因為true等於1。它是在pre-procesor偽指令中定義的,所以其中所有帶有true的代碼在編譯之前都會轉換為1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM