A little C++ curiosity...

36b416ed76cbaff49c8f6b7511458883
0
poita 101 Sep 22, 2009 at 16:19

This has no practical consequences for me, it’s just something that I’m curious about.

If I were to create a function

bool foo(bool a, bool b) { return a && b; }

And use it…

foo(false, function_with_side_effects());

Would the compiler be allowed to inline it such that the function with side effects isn’t called? In other words, could it inline it to this:

false && function_with_side_effects();

Again, this isn’t causing me any problems; it’s just a curiosity that recently crossed my mind.

5 Replies

Please log in or register to post a reply.

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 168 Sep 22, 2009 at 16:21

No; when calling a function all arguments are always completely evaluated.

36b416ed76cbaff49c8f6b7511458883
0
poita 101 Sep 22, 2009 at 16:55

Well, yes. I suppose the implication is that this rule applies to functions that are inlined as well?

What about overloads of operator&&? Are they all special functions, or are they only special for primitive types?

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 168 Sep 22, 2009 at 17:00

Yes; inlining a function doesn’t change the fact that all arguments are evaluated. As for overloads of operator&&, I’m 95% sure they behave just like regular functions, and the short-circuiting behavior only applies to the built-in operator&&.

36b416ed76cbaff49c8f6b7511458883
0
poita 101 Sep 22, 2009 at 17:40

Yay for consistency.

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Sep 22, 2009 at 20:05

@Reedbeta

Yes; inlining a function doesn’t change the fact that all arguments are evaluated. As for overloads of operator&&, I’m 95% sure they behave just like regular functions, and the short-circuiting behavior only applies to the built-in operator&&.

Correctamundo