0

I have a method in class which returns bool. This bool signifies if the call was successful or or not. Many a time users of this method misses to capture the bool

bool bar()
{
    return true; //or false in some cases
}


bool result = bar(); //
bar();// Can we get a warning or compiler error here

This is similar to Force function to return value and make compile error C# But the answers there are not applicable here.

I am using gcc 4.4.7

Community
  • 1
  • 1
SumitV
  • 186
  • 9

2 Answers2

3

The caller is free to ignore that value and the compiler will happily optimize it out. If you want the caller to be "forcefully" acknowledged of a failure, in a standard way in regard to both C++ and design, throw an exception because unhandled exceptions will call std::terminate.
Alternatively, set an internal value that forbids further operation as in std::ios.

edmz
  • 8,220
  • 2
  • 26
  • 45
2

Statements may be simple expressions (assignment is also a typed expression) - so generally no.

You can implement this as a runtime functionality though:

template<typename ResultType>
class CheckReturn {
    public:
        CheckReturn(ResultType value) : m_value(value), m_checked(false) { }
        ~CheckReturn(void) { assert(m_checked); }
        operator ResultType (void) { m_checked = true; return m_value; }

    private:
        ResultType m_value;
        bool m_checked;
};

then

CheckReturn<bool> foo() { return false; }
...
if(foo()) { } // ok
foo(); // assertion failure at runtime
BeyelerStudios
  • 4,243
  • 19
  • 38
  • wow! That is very intelligent. I am looking for a something so I don't have to change the signature. – SumitV Jul 08 '15 at 11:19
  • @NewCoder without changing the signature the only other way is black's suggestion: use exceptions for exceptional control flow (i.e. values that must be caught) - you can combine the two approaches (throw an exception in `~CheckReturn`) to avoid the (small) overhead of stack unrolling in *normal* control flow i.e. where you capture the return value. – BeyelerStudios Jul 08 '15 at 12:01