Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c - What advantage does _Bool give?

If the _Bool type acts like an integer and doesn't enforce that a value is true/false or 1/0, for example:

_Bool bools[] = {0,3,'c',0x17};
printf("%d", bools[2]);

> 1

What is the advantage of having that there? Is it just a simple way to coerce things to see how they would evaluate for 'truth-ness', for example:

printf("%d
", (_Bool) 3);
> 1

Or how is this helpful or useful in the C language?

question from:https://stackoverflow.com/questions/65650393/what-advantage-does-bool-give

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The advantage is legibility, nothing more. For example:

bool rb() {
  if (cond && f(y)) {
    return true;
  }

  return false;
}

Versus:

int rb() {
  if (cond && f(y)) {
    return 1;
  }

  return 0;
}

There's really no other benefit to it. For those that are used to working in C code without bool, it's largely cosmetic, but for those used to C++ and its bool it may make coding feel more consistent.

As always, an easy way to "cast to a boolean value" is just double negation, like:

!!3

Where that will reduce it to a 0 or 1 value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...