C Booleans

1. What is a Boolean?

  • A Boolean represents truth values:

    • True → 1

    • False → 0

  • Used in conditional statements, loops, and logical operations.

Note: C does not have a built-in bool type in older versions (C89/C90).
In modern C (C99 and later), you can use _Bool or stdbool.h for boolean variables.


2. Boolean Using _Bool

  • _Bool is a built-in type in C99.

  • Values: 0 (false) or 1 (true)

#include <stdio.h>

int main() {
_Bool flag = 1; // true
_Bool done = 0; // false

printf("Flag: %d\n", flag);
printf("Done: %d\n", done);

return 0;
}

Output:

Flag: 1
Done: 0

3. Boolean Using stdbool.h

  • Modern C allows bool type with true and false keywords.

#include <stdio.h>
#include <stdbool.h>

int main() {
bool isAvailable = true;
bool isFinished = false;

printf("Available: %d\n", isAvailable);
printf("Finished: %d\n", isFinished);

return 0;
}

Output:

Available: 1
Finished: 0

%d prints 1 for true and 0 for false.


4. Boolean in Conditional Statements

#include <stdio.h>
#include <stdbool.h>

int main() {
bool isRaining = true;

if (isRaining) {
printf("Take an umbrella.\n");
} else {
printf("No umbrella needed.\n");
}

return 0;
}

Output:

Take an umbrella.

5. Boolean in Expressions

  • Logical operators return 0 or 1 → Boolean result:

#include <stdio.h>
#include <stdbool.h>

int main() {
int a = 10, b = 5;

bool result;

result = (a > b); // true
printf("a > b: %d\n", result);

result = (a == b); // false
printf("a == b: %d\n", result);

result = (a > 0 && b < 0); // false
printf("a > 0 && b < 0: %d\n", result);

return 0;
}

Output:

a > b: 1
a == b: 0
a > 0 && b < 0: 0

6. Key Points

  1. Boolean represents true (1) or false (0).

  2. Use _Bool (C99) or stdbool.h for modern C programs.

  3. Boolean values are commonly used in if statements, loops, and logical operations.

  4. Logical operators like &&, ||, and ! produce Boolean results.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *