COP 3223H meeting -*- Outline -*- * Boolean expressions ** Boolean values ------------------------------------------ BOOLEAN VALUES IN C For purposes of conditionals (if-statements, conditional expressions) 0 non-zero With #include the type bool and two values: ------------------------------------------ ... is considered false ... is considered true ... false, true false is defined as 0, true as 1 _Bool is part of the C99 standard, but for future portability use and bool instead of 0, 1, and _Bool ** Boolean Expressions *** Boolean operators ------------------------------------------ OPERATORS ON BOOLEANS Negation: ! like Short-circuit operators: && like || like true && B == false && B == true || B == false || B == Bit-wise operators & | ~ ^ 07 & 07 == 05 & 07 == 01 & 07 == 00 & 00 == 07 | 00 == 05 | 07 == 05 | 02 == 05 | 03 == 03 | 00 == ~07 == ~06 == ~05 == ~04 == ------------------------------------------ ... not in Python ... and in Python ... or in Python ... B ... false ... true ... B (& answers) ... 07 ... 05 ... 01 ... 00 (| answers) ... 07 ... 07 ... 07 ... 07 ... 03 (~ answers, having declared these numbers as ints) ... 37777777770 ... 37777777771 ... 37777777772 ... 37777777773 etc... *** Boolean-valued expressions You rarely need to write true or false explicitly in a program, because most boolean values arise from other expressions... ------------------------------------------ BOOLEAN-VALUED EXPRESSIONS Comparisons have _Bool values: 2 < 3 3 > 2 2 == 2 2 != 3 !(2 == 3) 3 <= 3 2 <= 3 3 >= 2 3 >= 3 Be sure to use == for comparisons 2 = 2 // error! int v = 0; if (v = v) { // wrong! printf("true\n"); } else { printf("false\n"); } ------------------------------------------ Note the difference between == and = in C (as in Python)