简体   繁体   中英

Difference between void and non-void functions in C++

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?

If your function has no reason to return something, it shouldn't return anything, ie, 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, eg, because it can fail, it should return the corresponding result. Since the result will be meaningful, it won't be ignored, ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM