1

I think I might know the answer to this, but I wanted to make sure I fully understand.

I've written a Queue structure in C, as well as operations for use on a Queue struct. I would like to pop the queue, retrieving one element. This element would be the first parameter into my function. I would like to pop the queue again, retrieving the second element. This second element would be my second parameter.

For example:

e1 = pop(Q);
e2 = pop(Q);
myfunction(e1, e2);

I would like to do this is in a slicker way that doesn't require me to make two throwaway variables.

My assumption would be the following:

myfunction(pop(Q), pop(Q))

But I'm not 100% sure if this is correct.

Is this correct? Are there slicker ways of accomplishing this?

Sven
  • 127
  • 10
  • *slicker* doesn't mean better. While your assumption is syntactically correct it is prone to multiple runtime errors. – Jonny Henly Mar 30 '16 at 22:49

2 Answers2

2

The order of evaluation of function arguments is undefined, so the second fragment may or may not be equivalent to the first one.

In that case myfunction(pop(Q), pop(Q)) leads to undefined behaviour.

See also Compilers and argument order of evaluation in C.

Community
  • 1
  • 1
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

In addition to Michael's answer, if this is an often-repeated construct, you can also make a function myFunctionFromQueue(Q) which would abstract the boilerplate away.

Additionally, unless you're popping ints or similar, more realistic code would end up looking like:

e1 = pop(Q)
e2 = pop(Q)
myFunction(e1, e2)
manage_ownership(e1)
manage_ownership(e2)
Mark Nunberg
  • 3,551
  • 15
  • 18