1

I have simple question

Let's say I have two functions in C++:

void DoSomething(); 

and

bool DoSomething(); 

Is there any difference in memory or speed between these two functions?

And second question, related to first: I suppose that there is speed difference, as bool has to return some value. But I don't have to use return value at all. So, would it be good for me to declare DoSomething() as bool, just in case I decided to return something in the future?

2
  • 3
    Why don't you test it? Commented Nov 22, 2013 at 23:23
  • 1
    The difference is likely to be negligible - what's prompting your concern? Commented Nov 22, 2013 at 23:23

2 Answers 2

9

If your function has no reason to return something, it shouldn't return anything, i.e., it should return void. There is no point in giving a function which doesn't produce any result an artificial return value.

If you function has a reason to return something, e.g., because it can fail, it should return the corresponding result. Since the result will be meaningful, it won't be ignored, i.e., there is no optimization potential for not returning value.

Where things do become interesting is when returning massive objects: the potential copy happening may be expensive and there is also a speed advantage with respect to reusing memory. However, these considerations don't apply to any of built-in types.

Sign up to request clarification or add additional context in comments.

1 Comment

Also note that even the “potential copy” is pretty much rare. Most data types can be moved and otherwise the compiler will usually apply RVO.
0

In terms of memory and speed, the difference between void DoSomething(); and bool DoSomething(); is likely negligible. Choosing between them depends on the function's intended purpose: use void for actions without a return value and bool if you foresee needing to convey a boolean result. The unused return value may not significantly impact performance, but it's good practice to align the return type with the expected behavior of the function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.