Home Misc How to use boolean type in C?

How to use boolean type in C?

by nikoo28
0 comment

Question:

C does not have the boolean data type by default. Is there a way by which we can implement it?

In C language, we do not have the boolean datatype by default. That means we cannot do something like

if(true)
{
    // perform some commands
}
else
{
    // perform the else commands
}

We can do this in C++ and JAVA. However, we have an alternative method to achieve the same functionality. Before moving on to the implementation it is important to know that in C, if a value is ‘0 (zero)’ it is treated as false, and any other value other than ‘0’, is treated as true.
That means if we do something like

if(2)
{
    // THIS PORTION WILL RUN
}
else
{
    // this will NOT
}

if(0)
{
    // this will NOT RUN
}
else
{
    // THIS PORTION WILL RUN
}

while(1)
{
    // an example of an infinite loop
}

Thus, to implement the boolean data type we can do it by 3 methods:-

Method 1:-

typedef int bool;
#define true 1
#define false 0

Method 2:-

typedef int bool;
enum { false, true };

Method 3:-

typedef enum { false, true } bool;

All 3 methods, basically perform the same functionality. It assigns the value ‘1’ to true and ‘0’ to false. This way we define a custom data type. and the C pre-processor takes care of the rest of the stuff.

Here is a sample program that illustrates the use of this custom boolean datatype in C.

#include<stdio.h>

//defining the boolean datatype
typedef int bool;
#define TRUE 1
#define FALSE 0

//defining the main function to test
int main(void)
{

	//testing the methodology
	if(FALSE)
	{
		printf("I CANT PRINT");
	}
	else
	{
		printf("YOU SUCCESSFULLY IMPLEMENTED boolean DATATYPE");
	}

	//An example of infinite loop
	while(TRUE)
	{
		printf("This loop will run forever");
	}

	return 0;
}

You may also like

Enclose codes in [code lang="JAVA"] [/code] tags

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More