Home > Software design >  Return True or 1?
Return True or 1?

Time:01-05

As I know, Boolean is basically a char datatype, one byte, 0x00 or 0x01. Also, as I know, Integer is multiple bytes.

bool foo () {
    return true; // I guess is 0x01 one byte
    return 1; // I guess is 0x00000001 four bytes (depend on the platform)
}

1 - Why do both returns work?

2 - What's the best practice to follow?

CodePudding user response:

As I know, Boolean is basically a char datatype, one byte, 0x00 or 0x01

That is not the case, the size of bool type is implementation-defined and is not specified in the C standard, it is usually defined in stdbool.h as of C99 and is normally something like:

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

Before that it wasn't even a mandated type. You can say that in some implementations it's equivalent to a single byte, but not always.

What's the best practice to follow?

The best practice is an opinion based question, still I would advise to use true/false because it's a pattern used in pretty much all the languages and it'll surely be easier to understand.

Why do both returns work?`

In C, any non-zero value is considered to be true (this includes negative values) in a boolean context, whereas 0 is considered to be false.

CodePudding user response:

As others have explained, the size of a bool is not specified by the standard, so a compiler implementation is free to use any size as long as it can hold the values 0 and 1.

My clear recommendation is to use a bool type if the information is true/false by nature. Using an integer as boolean can lead to subtle errors. Consider the following (inspired by a real-life bug):

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

uint8_t isThisTrueInt(void)
{
    int x = 256;
    return x;
}

bool isThisTrueBool(void)
{
    int x = 256;
    return x;
}

int main(void)
{
    printf("%s\n", (isThisTrueInt())?"true":"false");
    printf("%s\n", (isThisTrueBool())?"true":"false");
    return 0;
}

The result is:

false
true

The point being that converting 256 to an 8-bit integer truncates to 0, i.e. "false" while conversion to bool will give "true" for any non-zero integer.

CodePudding user response:

Here is what the C 2017 standard says about the bool (aka _Bool) so "basically a char" is not correct:

An object declared as type _Bool is large enough to store the values 0 and 1. (6.2.5)

return 1 works due to automatic type conversion:

When any scalar value is converted to _Bool , the result is 0 if the value compares equal to 0; otherwise, the result is 1 (6.3.1.2)

There is no "best practice" as far as I know. Unless I missed it I don't see it covered in MISRA C, for instance, but it may be covered in coding guidelines for your project. Personally, I use 0 and 1 simply because it's shorter to write.

  •  Tags:  
  • c
  • Related