Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...