using a bool in normal maths

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have a bool defined in stdbool.h as:

#define bool _Bool
#define true 1
#define false 0

Now if a bool called negative. Can I do:

bool negative;
uint8_t k = 0;
uint8_t my_buffer[8];

if (a < 0)
 negative = true;
else
 negative = false;

my_buffer[k + negative] = 99;

Or can I do:

i = k +negative + 22;

I.e. is true defined as 1 by standard, or is the complier variable?

Ben
-Using IAR (& ocasionally CodeVision)
0.7734
1101111011000000110111101101

Last Edited: Wed. Apr 16, 2008 - 04:05 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You can do all sorts of things, and they will most probably work. true is not a keyword in C. Logical true is only defined as NOT zero. So any expression with a non-zero result is "true". You can however rely on zero being "false". These names are "quoted" because they are only normal identifiers.

It is wise to use "boolean types" only in logical expressions and regular variables in arithmetic expressions.

And I would suggest that you assign with:

negative = (a < 0);  // instead of = (a != 0)

You can probably see all sorts of tricks with 1 and 0. Avoid them. The compiler knows these tricks too, and will only use safe tricks. So write using correct types and let the compiler do its job.

David.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
Logical true is only defined as NOT zero

This is untrue. A "true" result of a logical operator will be 1 when assigned to an integer (so negative in your example will be 1 if a is less than 0). However, in the reverse, any non zero integer will be interpreted as true when used in a logical expression.

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Edit: I was wrong. I have looked it up in the original K & R.
It was NEVER implementation dependent.
true is always 1, and false is always 0 but neither are keywords.

In any case, it is bad practice to mix types.

David.

Last Edited: Wed. Apr 16, 2008 - 10:01 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The compiler interpret every non zero value as true.
But the compiler must always return 1, if an expression was true.
E.g.:

y = !!x;

Then:

...
x=-1: y=1
x=0: y=0
x=1: y=1
x=2: y=1
...

Peter

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Just out of interest, while your defintions match stdbool.h, wouldn't it be better to simply #include rather than reinventing the wheel?