Home > Net >  no comparison in if() judgement but seems give a boolean value
no comparison in if() judgement but seems give a boolean value

Time:06-27

if(!word.size()){
        return true;
    }

whole code screenshot

how here use string.size() lonely to return a boolean value?

I googled the string.size() method although i already know it returns a int value,but here it works like a true/false method;

CodePudding user response:

Lots of things in C can be coerced to Booleans. Off the top of my head.

  • Booleans are trivially convertible to Booleans
  • Numbers (int or double) can be converted to Boolean; zero is false and anything else is true
  • Streams (like fstream instances or cout, for instance) can be converted to Boolean and are true if the stream is in "good" condition or false if there's a problem

As indicated in the comments, you shouldn't use this in real code. if (!word.size()) is silly and confusing an should only be seen in code golf challenges. Coding isn't just about making the computer understand what you mean; it's about making sure future readers (including yourself six months down the line) understand as well. And if (word.empty()) conveys the exact same intent to the computer but is much more understandable to the human reader at a glance.

So why does C allow this if it's discouraged? Historical reasons, mostly. In the days of C, there was no dedicated bool type. Comparisons returned an integer, and the convention was that 0 meant "false" and anything else (usually 1) meant true. It was the programmer's job to remember which things were Booleans and which were actual integers. C came along and (rightly) separated the two, making a special type called bool. But for compatibility with C, they left in the old trick of using integers as Booleans. Successor languages like Java would go on to remove that capability. if (myInteger) is illegal in Java and will give a compiler error.

CodePudding user response:

The language checks if the condition inside the conditional is true or false. In this case, the int value gets converted into a boolean. If the size returns 0 this will get converted to false, any other value will be converted to true.

  •  Tags:  
  • c
  • Related