473,606 Members | 2,409 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Boolean data type?


I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?

I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from? For example

int QueryBit(char unsigned const *const pc, unsigned const index)
{
return *pc & (1U << index);
}

(Let's leave alone for the moment the issue of whether this should
instead be a macro)

I suppose I'm asking two questions:

a) What type is commonly used for booleans?
b) What type is commonly used for booleans when you've to go easy
on memory consumption?

Martin

Sep 21 '07 #1
14 9486
Martin Wells wrote:
>
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?
int a = 5, b = 6;

if (!a == !b) DoSomething; /* This will execute */

--
pete
Sep 21 '07 #2
Martin Wells wrote:
>
I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from? For example
I suppose I'm asking two questions:

a) What type is commonly used for booleans?
b) What type is commonly used for booleans when you've to go easy
on memory consumption?
In that case, if I didn't have access to a C99 compiler, or a compiler
with bool as an extension, I'd use an enum. Most embedded compilers I
have used have options to minimise the size of enums by using the
smallest type than holds the range of the enum values.

--
Ian Collins.
Sep 21 '07 #3
On Sep 21, 4:22 pm, Martin Wells <war...@eircom. netwrote:
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?

I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from? For example

int QueryBit(char unsigned const *const pc, unsigned const index)
{
return *pc & (1U << index);

}

(Let's leave alone for the moment the issue of whether this should
instead be a macro)

I suppose I'm asking two questions:

a) What type is commonly used for booleans?
b) What type is commonly used for booleans when you've to go easy
on memory consumption?
If you have C99 {where _Bool is a type} then:

ISO/IEC 9899:1999 (E) ©ISO/IEC
7.16 Boolean type and values <stdbool.h>
1 The header <stdbool.hdefin es four macros.
2 The macro
bool
expands to _Bool.
3 The remaining three macros are suitable for use in #if preprocessing
directives. They are:
true
which expands to the integer constant 1,
false
which expands to the integer constant 0, and
_ _bool_true_fals e_are_defined
which expands to the integer constant 1.
4 Notwithstanding the provisions of 7.1.3, a program may undefine and
perhaps then redefine the macros bool, true, and false.213)
213) See "future library directions" (7.26.7).
252 Library §7.16

Else just use enums or macros. Typically as enum:

typedef boolean_type {false=0, true} bool_t;

Typically as macro:

#ifndef FALSE
#define FALSE 0
#endif

#ifndef TRUE
#define TRUE !FALSE
#endif

Sep 22 '07 #4
Martin Wells <wa****@eircom. netwrites:
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?
<http://www.c-faq.com/>, section 9.
I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from?
[...]

Using a type smaller than int for booleans is likely to save space,
but is also likely (but not certain) to increase code size. If your
CPU can load, store, and manipulate bytes as easily as words, using a
1-byte type makes sense; if not, int is likely to be a good choice.

If you want to have, say, large arrays of booleans, the tradeoffs
change. It might even make sense to store a boolean value in each bit
(but you'll have to write your own bitwise masking and shifting code
to do this -- or find something that's already been written).

Assuming C99's _Bool is not available, my favorite form is something
like:

typedef enum { false, true } bool;

This allows the compiler to decide how big to make a bool. But watch
out for name collisions if another library you're using defines its
own boolean type.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 22 '07 #5
Martin Wells wrote:
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?
It used to be that C programmers did not rely on the boolean crutch,
since various kinds of integers serve quite well without losing
information. However, for some reason this expensive way to store
single bits has enough appeal that we now have:

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

int main(void)
{
bool a_bool = 5, b_bool = 6; /* <stdbool.hcause s 'bool' to
expand to '_Bool' */
_Bool a_Bool = 5, b_Bool = 6;
unsigned int a_int = 5, b_int = 6;

printf("using 'bool' versions of a and b\n"
"a_bool = %u, compares %sequal to 'true'\n"
"b_bool = %u, compares %sequal to 'true'\n"
"the value of a_bool == b_bool is %u\n"
"the value of (a_bool == b_bool) == true is %u\n\n",
a_bool, (a_bool == true) ? "" : "not ",
b_bool, (b_bool == true) ? "" : "not ",
a_bool == b_bool, (a_bool == b_bool) == true);
printf("using '_Bool' versions of a and b\n"
"a_Bool = %u, compares %sequal to 'true'\n"
"b_Bool = %u, compares %sequal to 'true'\n"
"the value of a_Bool == b_Bool is %u\n"
"the value of (a_Bool == b_Bool) == true is %u\n\n",
a_Bool, (a_Bool == true) ? "" : "not ",
b_Bool, (b_Bool == true) ? "" : "not ",
a_Bool == b_Bool, (a_Bool == b_Bool) == true);

printf("using 'unsigned int' versions of a and b\n"
"a_bool = %u, compares %sequal to 'true'\n"
"b_bool = %u, compares %sequal to 'true'\n"
"the value of a_int == b_int is %u\n"
"the value of (a_int == b_int) == true is %u\n\n",
a_int, (a_int == true) ? "" : "not ",
b_int, (b_int == true) ? "" : "not ",
a_int == b_int, (a_int == b_int) == true);

return 0;
}

[output]
using 'bool' versions of a and b
a_bool = 1, compares equal to 'true'
b_bool = 1, compares equal to 'true'
the value of a_bool == b_bool is 1
the value of (a_bool == b_bool) == true is 1

using '_Bool' versions of a and b
a_Bool = 1, compares equal to 'true'
b_Bool = 1, compares equal to 'true'
the value of a_Bool == b_Bool is 1
the value of (a_Bool == b_Bool) == true is 1

using 'unsigned int' versions of a and b
a_bool = 5, compares not equal to 'true'
b_bool = 6, compares not equal to 'true'
the value of a_int == b_int is 0
the value of (a_int == b_int) == true is 0
Sep 22 '07 #6
Martin Wells wrote:
>
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators
as if they were logical operators:
There is no boolean type in C90. C99 has a _Bool type.
>
.... snip ...
>
I suppose I'm asking two questions:

a) What type is commonly used for booleans?
b) What type is commonly used for booleans when you've to
go easy on memory consumption?
>From N869:
[#6] For each of the signed integer types, there is a
corresponding (but different) unsigned integer type
(designated with the keyword unsigned) that uses the same
amount of storage (including sign information) and has the
same alignment requirements. The type _Bool and the
unsigned integer types that correspond to the standard
signed integer types are the standard unsigned integer
types. The unsigned integer types that correspond to the
extended signed integer types are the extended unsigned
integer types. The standard and extended unsigned integer
types are collectively called unsigned integer types.27)

If you #include <stdbool.hthe n bool is defined (as _Bool), and:

B.15 Boolean type and values <stdbool.h>

bool
true
false
__bool_true_fal se_are_defined

Note that this is only in C99.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Sep 22 '07 #7
Ian Collins wrote:
Martin Wells wrote:
>I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from? For example
I suppose I'm asking two questions:

a) What type is commonly used for booleans?
b) What type is commonly used for booleans when you've to go easy
on memory consumption?

In that case, if I didn't have access to a C99 compiler, or a compiler
with bool as an extension, I'd use an enum. Most embedded compilers I
have used have options to minimise the size of enums by using the
smallest type than holds the range of the enum values.
I tried and adopted enum until I got a new version of the compiler that
supported _Bool. To my astonishment, _Bool generated much more efficient
code than the enum.
Still, honestly, there are very few precious cases where bool of any
sort has merits. They AFAIK are limited to temporarily storing results
of bulky comparisons and used only to improve readability (since the
compiler should optimize them out).
bool return type looks evil since the compiler effectively does
something like return !!x; it's an overhead I could do without.
-- Ark
Sep 22 '07 #8
On 2007-09-21 23:22, Martin Wells <wa****@eircom. netwrote:
>
I come from C++, and there's a type called "bool" in C++. It works
exactly like any other integer type except that when promoted, it
either becomes a one or a zero, so you can you bitwise operators as if
they were logical operators:

bool a = 5, b = 6;

if (a == b) DoSomething; /* This will execute */

What type is commonly used in C for playing around with boolean
values?

I'm writing code for an embedded systems project so I'll *really* have
to watch how much memory I'm using... so would it be wise to be
returning "int" from functions that I would otherwise (in C++) return
a bool from? For example

int QueryBit(char unsigned const *const pc, unsigned const index)
{
return *pc & (1U << index);
}
Worrying about the memory consumption of return types is probably
futile. On most systems the return value is passed in a register (if it
fits), so it always takes the same space and that space isn't in memory.

Also worrying about the size of simple variables probably doesn't make
much sense unless you really have a lot of them or are making heavy use
of recursive functions.

Where is the size really matters is in arrays. Storing boolean values in
an int[] wastes a lot of space (probably 15 or 31 bits per value,
depending on your platform). By using bool (if available), enum or char,
you may be able to reduce the overhead to 7 bits per value. But an array
element can never use less than 8 bits in C, so if that's still too
much, you should consider storing them in an array of unsigned int,
where each element holds the appropriate number of bits.
hp
--
_ | Peter J. Holzer | I know I'd be respectful of a pirate
|_|_) | Sysadmin WSR | with an emu on his shoulder.
| | | hj*@hjp.at |
__/ | http://www.hjp.at/ | -- Sam in "Freefall"
Sep 22 '07 #9

"Martin Wells" <wa****@eircom. netwrote in message
news:11******** *************@n 39g2000hsh.goog legroups.com...
>
What type is commonly used in C for playing around with boolean
values?

a) What type is commonly used for booleans?
b) What type is commonly used for booleans when you've to go easy
on memory consumption?
int by convention.

So

int is_prime(int N)

for instance.

Not

typedef int BOOL;

BOOL is_prime(int N)

bool breaks libraries. You don't want everyone who happens to cut and paste
your is_prime function to be tied to BOOL throughout his code.

However unsigned char would work. (A pathological implementation could make
1 a trap value for characters).

Space is only a problem when you need several booleans on the go - eg an
array of a thousand of the things.

Method 1: use a bitfield. This will often save the most. Typically there
will be a integer field that doesn't need the full 32 bits and you can raid
for the boolean, thus giving you a zero memory footprint.
Method 2: use unsigned char for the array, convert to in the minute you read
and write it. This is very simple and fast.
Method 3: write a getbit() and setbit() function to manage a flat array of
unsigned chars. This is a nuisance, but gives you total control, over bit
packing. It will probably be slightly slower than the bitfield, and
considerably slower than the char array.
Method 4: (for the crazed). Typically you can compress a bitstream. This
will really squeeze down your memory take, at a cost of massive overhead.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Sep 22 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
8609
by: Ramprasad A Padmanabhan | last post by:
Hello all, On my linux box ( redhat 7.2 ), I have been using char as a boolean data type. In order to save on the number of bytes as compared to using int or short int. typedef char boolean; boolean x; x=1;
6
17754
by: Bry | last post by:
I'm having problems writing (and reading) boolean data to the registry. // Write a boolean value to the registry // I've not included the obvious bits of code in these samples bool myBool = true; myRegistryKey.SetValue("SomeValue", myBool); This gives me a registry value with string data containing "True" // Read my boolean data back from the registry
10
16399
by: dba123 | last post by:
Why am I getting this error for Budget? Error: An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code Additional information: String was not recognized as a valid Boolean. Public Sub UpdateCustomer_DashboardGraphs(ByVal sender As Object, ByVal e As System.EventArgs)
2
14762
by: John | last post by:
My application needs to call Oracle function using oracle client 9.2. The oracle function returns boolean value from its returned parameter. The name space that I used is system.data.oracleclient. found out there is no boolean type in Oracle parameter in OracleType. How can I get the returned value from function call in my code? Thanks in advance
7
7077
by: Pep | last post by:
This is getting weird. I have to keep moving between visual c and gnu c++ compilers and now have come across a problem that seems to relate to the boolean datatype. I have a method that is defined as boolean isOkay(string var) { ... some code ...
76
4864
by: KimmoA | last post by:
First of all: I love C and think that it's beautiful. However, there is at least one MAJOR flaw: the lack of a boolean type. OK. Some of you might refer to C99 and its _Bool (what's up with the uppercase 'B' anyway?) and the header you can include (apparently) to get a real "bool". This isn't my point, however -- it should have been there from the beginning. char is a small int. We all know that. However, "char some_bool = 0;" simply...
2
6032
by: jobs | last post by:
What's messed up here is that i have close to identical code that is working perfectly, only difference is that code uses sqldatasource control instead objectdatasource used here. Getting this error during the update: Server Error. To return to your data and retry, use the BACK button System.ArgumentException: Object of type 'System.Int16' cannot be converted to type 'System.Boolean'. at System.RuntimeType.CheckValue(Object value,...
5
33052
by: Jeff | last post by:
Hey ..net 2.0 in my c# code I retrieve a value from a column in database (sql server 2000) (using SqlReader) this database column has the datatype Bit! Now I'm looking a way to cast this bit value into an .Net boolean variable Boolean test = (Boolean) _SqlReader; //this throws an
19
14763
by: tshad | last post by:
I have a value in my sql table set to tinyint (can't set to bit). I am trying to move it into a boolean field in my program and have tried: isTrue = (int)dbReader and isTrue = Convert.ToBoolean((int)dbReader)
0
8016
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7955
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8440
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
5966
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5466
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3937
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3980
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1300
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.