w3resource

Boolean values in C language

C - Using boolean values in C

Option – 1:

#include <stdbool.h>

The header stdbool.h in the C Standard Library for the C programming language contains four macros for a Boolean data type. The macros as defined in the ISO C standard are :

  • bool which expands to _Bool
  • true which expands to 1
  • false which expands to 0
  • __bool_true_false_are_defined which expands to 1
This header was introduced in C99.

Example: boolean values in C using stdbool.h

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

int main(void) {
    bool color = true;  // Could also be `bool color = 1;`
    while(color) {
        printf("This will run as long as color is true.\n");
        color = false;   
    }
    printf("color is false!\n");
    return 0;
}

Output:

This will run as long as color is true.
color is false!

Option – 2:

typedef enum { F, T } boolean;

Example: Using typedef enum { F, T } boolean;

#include <stdio.h>

typedef enum {
   F, T
}
boolean;


int main(void) {
	
	boolean color = T; 
    while(color) {
        printf("This will run as long as color is true.\n");
        color = F;   
    }
    printf("color is false!\n");
    return 0;
}

Output:

This will run as long as color is true.
color is false!

Contribute your code and comments through Disqus.



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M