Removing extra spaces

Pages: 12
How could you use the boolean type?

Sorry, I was coding in C style in a C++ project and forgot to add stdbool.h
http://pubs.opengroup.org/onlinepubs/007904875/basedefs/stdbool.h.html

In C bool isn't a built-in type; it's a #define of _Bool (at least in GCC; other compilers might use a typedef, I guess.)

Andy

PS Visual C++ does not provide stdbool.h in version 2012 and earlier (I don't know about 2013 ?). So you will have to lift a version from the internet or elsewhere.

I use one from here (the version in the response, not the one in the orig question)

interfacing with stdbool.h C++
http://stackoverflow.com/questions/25461/interfacing-with-stdbool-h-c

Visual C++ does provide stdint.h from version 2010.
Last edited on
Oops! I must have accidentally done something to it...

In C, a boolean is just a non-zero value. You'll see a lot of code like:

int isspace( int c )

The return value is either zero or it is not. That is why things like the following work:

1
2
3
4
5
void f( const char* s )
  {
  if (!s) return;
  ...
  }

On line 3 it is checking to see if the pointer value is zero or non-zero, treating it like a boolean.

Before C99, a lot of people would add things to C code to make it obvious that a boolean value is involved:

 
typedef int bool;
 
#define BOOL int 

and

1
2
#define FALSE (0)
#define TRUE (1)  /* or something other than zero */ 

Leading to:

1
2
3
4
5
6
7
BOOL iswhatever( char c )
  {
  for (...)
    if (...)
      return FALSE;
  return TRUE;
  }


Now that C99 is around, you can easily use bool normally:

1
2
3
4
5
6
7
bool isall( int xs[], unsigned len, (int (*f)(int) )
  {
  for (len--)
    if (!f( xs[ len ] ))
      return false;
  return true;
  }

Etc.

Hope this helps.

[edit] fixed a typo
Last edited on
Duoas, Thanks for explaining about the boolean type.

Andy, I use GCC compiler, so I think this library will work fine. Thnk you!
Topic archived. No new replies allowed.
Pages: 12