
C語(yǔ)言中的真/假和0/1在不同的情境下具有不同的意義,清楚地對(duì)他們進(jìn)行區(qū)別有助于正確理解程序,并巧妙地解決一些問(wèn)題。
在邏輯表達(dá)式中,0表示假,非0表示真
(資料圖)
int main(){ if (-1) { //執(zhí)行 printf("hehe\n"); } if (0) { //不執(zhí)行 printf("haha\n"); } return 0;}
在布爾類(lèi)型中,true定義為 1,false 定義為0
C11:
The remaining three macros are suitable for use in #if preprocessing directives. Theyare
true
which expands to the integer constant 1,
false
which expands to the integer constant 0, and
_ _bool_true_false_are_defined
which expands to the integer constant 1.
V.S.編譯器?stdbool.h
?中對(duì)??true?
?和??false?
??的定義:
#ifndef _STDBOOL#define _STDBOOL#define __bool_true_false_are_defined 1#ifndef __cplusplus#define bool _Bool#define false 0#define true 1#endif /* __cplusplus */#endif /* _STDBOOL */
關(guān)系表達(dá)式的返回值為 0 或 1,且具有??int?
?類(lèi)型
C99:
??6??Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.?92)??The result has type int.
標(biāo)準(zhǔn)中也給出了像??a?這樣的表達(dá)式的處理方法:
The expression a
問(wèn)題:判斷字符串是否合法,該字符串至少出現(xiàn)大寫(xiě)字母、小寫(xiě)字母和數(shù)字中的兩種類(lèi)型
可以將三種類(lèi)型的元素出現(xiàn)個(gè)數(shù)分別計(jì)數(shù),利用下面的表達(dá)式判斷:
if((upper_count > 0) + (low_count > 0) + (digit_count > 0) >= 2){ //符合條件}
標(biāo)簽: 關(guān)系表達(dá)式 邏輯表達(dá)式 布爾類(lèi)型