Bob Shannon
Bob Shannon

Reputation: 648

Returning true or false in c++

When I run a method of type bool in c++ with a return statement like so:

bool method() {
    return true;
}

there is no output at the console. To get output, I have to do:

bool method() {
    cout << "true";
    return true;
}

Is this the right approach?

Upvotes: 1

Views: 80377

Answers (4)

Shantanu_Pratap
Shantanu_Pratap

Reputation: 1

You can go with this approach if wanna print "true/false". Only works if you're declaring function without any access specifier.

bool method() {
cout<<std::boolalpha;
return true;}



bool method() {
cout<<std::boolalpha
cout << "true";
return true;}

Upvotes: 0

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

It is usually a good idea to separate the logic of your program from the input/output part of it. That way, you can change the logic without needing to change the display and vice versa.

An example of that might be (I've made it a bit less trivial):

int operation(int a, int b) {
    return a + b; 
}

void process() {
    int a, b;
    std::cin >> a >> b; 
    std::cout << operation(a, b);
}

That should be followed even in languages that directly print the output of the executed function (but it's oftentimes not for sake of "simplicity" in example programs). It makes a massive difference when designing larger systems.

You can find out more about it by googling "Model-View-Controller" or simply "separating logic from IO".


To get to your particular example, you made a function that's distinctively "logic", and that's a good thing. You could add the printing statement inside, but typically it's better, again, to separate the concerns.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

This program is compiled and executed successfully and outputs 1 that is the value of true.

#include <iostream>

bool method() {
    return true;
}
int main()
{
   std::cout << method() << std::endl;
}

If you want that instead of 1 there will be literal true you can write

#include <iostream>
#include <iomanip>

bool method() {
    return true;
}

int main()
{
   std::cout << std::boolalpha << method() << std::endl;
}

The problem maybe is also that your program after executing closes the window and you have no time to see the result. You should insert some input statement in the end of the program that it would wait until you enter something.

Upvotes: 8

Manu343726
Manu343726

Reputation: 14174

C++ is not an interpreted language, like python, its a compiled language. So you don't write the function call on a interpreter and it prints the result. You are compiling your program and executing it later. So if you need to output something to the console in your program, you have to write an instruction to do that ( like std::cout << does ).

Upvotes: 5

Related Questions