Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are (bool)(i & 1) and i % 2 == 1 same?

Are (bool)(i & 1) and i % 2 == 1 always same where i is int?

Note: saying always I mean for all platforms (even when a byte is 16 bit) and for all standards of C and C++.

Edit:

For all standards of C and C++ where bool exist.

like image 800
Mihran Hovsepyan Avatar asked Jun 22 '11 10:06

Mihran Hovsepyan


People also ask

Is bool true 1 or 0?

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. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Is a bool 1 byte?

bool The bool type takes one byte and stores a value of true (1) or false(0).

What values can a bool be?

There are just two values of type bool: true and false. They are used as the values of expressions that have yes-or-no answers.

What data type is a bool?

In computer science, the Boolean (sometimes shortened to Bool) is a data type that has one of two possible values (usually denoted true and false) which is intended to represent the two truth values of logic and Boolean algebra.


1 Answers

No.

1s' complement representation of int, the representation of -1 is 1 ... 10, so they differ.

Anyway, i % 2 can be negative for negative i (indeed it's required to be in C99 when it's not 0), and hence not equal to 1 for negative odd numbers.

like image 53
Steve Jessop Avatar answered Sep 17 '22 21:09

Steve Jessop