Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char or Int for boolean value in C?

Tags:

c

I find that there is no native bool type. People either use int or char - though it seem that int might be more frequently used than char? Is this true?

My first impulse was to use char as it is a smaller data type, but there something I've missed? Is int better for boolean values, and if so - why?

like image 749
thomthom Avatar asked Mar 01 '12 17:03

thomthom


People also ask

What is the datatype for boolean in C?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true.

Can boolean be stored in int?

Nope, bools are designed to only store a 1 or a 0.

Can you declare a boolean in C?

Syntax to Declare Boolean Data Types in C:To declare a boolean data type in C we have to use a keyword named bool followed by a variable name. bool var_name; Here, bool is the keyword denoting the data-type and var_name is the variable name. A bool takes in real 1 bit, as we need only 2 different values(0 or 1).

Is boolean an integer type?

Boolean values still behave as integers, can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting.


1 Answers

There is a _Bool in C99, and a bool if you include stdbool.h.

If you don't have it (a decently modern compiler), use int, it's usually the fastest type. The memory savings of using char are likely negligible.

like image 73
cnicutar Avatar answered Sep 17 '22 19:09

cnicutar