Boolean types using function pointers

There are many ways to use Boolean  date types in C. C99 standard library <stdbool.h> or many others, one just need to "google".
While reading book "Understanding and Using C Pointers" it came to my mind that another way to define Boolean type is C pointers. Something like this:

typedef void (*bool)();
void true() {}
void false(){}

To use it we can simply do that:

bool is_correct;
is_correct = false;


Here is a working example:


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

typedef void (*bool)();
void true() {}
void false(){}

int main(){
  bool is_correct;

  is_correct = false;

  if(is_correct == false){
    printf("Is NOT correct.\n");
  }else{
    printf("Is CORRECT\n");
  }

  return 0;
}



Why it works? Because in C you can compare pointers. And our types "false" and "true" are pointers to functions.

This is just an idea and in really code it is, of course, better use standard library.

Comments

Popular posts from this blog

Asterisk Queues Realtime Dashboard with amiws and Vue

YAML documents parsing with libyaml in C