Search code examples
c++boolean-operations

boolean function uses in c++


#include <iostream>
#include<string>

bool findG( const std::string name)
{
    return name.length() >= 3 && name[0] == 'H'; 
}

bool NotfindG( const std::string name)
{
    return !findG(name); 
}

int main()
{
    std::string name = "agHello";


    if(findG(name)) 
    {
        std::cout << "It found Hello\n";
    }
    else
    {
        std::cout << "It did not find hello \n";
    }
}

What you see a boolean function that returns if it finds the string that is given in the argument.

I understand what the function is doing. What my interest is to know what the activities of the function NotfindG in the above code?

bool NotfindG( const std::string name)
{
    return !findG(name); 
}

I saw someone was using this but to me, the function should work even without the boolean function NotfindG (i mean in the else condition). Could you give me some reasoning about why someone would use that?


Solution

  • In your example code, nothing actually calls NotFindG, so indeed there's just no need for it.

    A general-purpose Not* variation of a bool function is of limited use, but I can come up with a few justifications:

    • It does little harm by existing; if a caller feels it's better to use it, then go ahead.
    • It could be in a series of similar functions, so even if this particular function doesn't seem necessary it's just a matter of being consistent with some kind of style.
    • FindG looks specific to some kind of business logic, which means wrapping as much of it as possible may be a good idea. Maybe NotFindG is a specific requirement that could theoretically be something other than FindG, so it's technically more accurate to call NotFindG than !FindG. Heck maybe FindG is the one that should be removed if this is the case.