Skip to content

boolean data type causes logic errors. #2147

Closed
@Chris--A

Description

@Chris--A

It has come to my attention that the boolean type alias produces results differing to the C++ standard boolean type bool.

Consider this sketch:

void setup() {
  Serial.begin(9600);
  Serial.println( true == (bool) 57 ? "true" : "false" );
  Serial.println( true == (boolean)57 ? "true" : "false" );
  Serial.println( true == bool( true ) ? "true" : "false" );
  Serial.println( bool( 1 | 2 | 4 | 8 ) == boolean( 1 | 2 | 4 | 8 ) ? "true" : "false" );
  Serial.println( true == false + 1 ? "true" : "false" );
  Serial.println( true + true == true ? "true" : "false" );
  Serial.println( bool( true + true ) == true ? "true" : "false" );
  Serial.println( boolean( true + true ) == true ? "true" : "false" );
}

void loop(){}

Using this sketch with boolean declared as a typedef to uint8_t ( which is what the current core does ) the output to the serial monitor is:

true
false
true
false
true
false
true
false

Whereas, after changing the core to allow a boolean to be declared as bool. The sketch produces this output:

true
true
true
true
true
false
true
true

It appears boolean has been implemented to provide boolean functionality with some C code in the Arduino core. I recommend changing the core so by the time boolean is seen by a sketch it is either a typedef or #define to the real bool type.

These are the modifications I propose be implemented in Arduino.h

#ifdef __cplusplus
    typedef bool boolean;
#else
    typedef uint8_t boolean;
    #define false 0
    #define true !false
#endif

On a side note, the defines for true and false should be removed. Boolean's ( the real one ) are subject to integral promotion and convert to either 0 or 1. Also the standard forbids macros named the same as keywords. If the C code needs defines, use TRUE & FALSE instead.

I have created a pull request here:
#2151

I also have a proof I'm in the middle of writing as to why the defines true and false need to be removed from the C++ side. I will add it soon.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions