Nick Mack
Nick Mack

Reputation: 75

Variadic functions arguments bad order in some cases

I was trying to reduce my code and I found something weird with variadic functions (it's most certainly due to my lack of knowledge though)

So I have that piece of code that works :

void Text::textTypePtr(Root* text, ...)
{
  va_list args;
  va_start(args, text);
  Interact::ModifiedKey modKey = va_arg(args, Interact::ModifiedKey);
  Keyboard::Key key = va_arg(args, Keyboard::Key);  
  static_cast<Text*>(text)->textType(modKey, key);
  va_end(args);
}

and then, this piece of code that reverses the args order

void Text::textTypePtr(Root* text, ...)
{
  va_list args;
  va_start(args, text);
  static_cast<Text*>(text)->textType(va_arg(args, Interact::ModifiedKey), va_arg(args, Keyboard::Key));
  va_end(args);
}

I'm now scared that the first piece of code worked by some miracle, can someone maybe help me to understand what's going on?

Upvotes: 0

Views: 121

Answers (1)

Barmar
Barmar

Reputation: 781848

The first version is correct. Statements are executed in order, so you can be confident the first variadic argument will be assigned to modKey and the second will be assigned to key.

The second version is depending on unspecified behavior. The relative order of evaluation of arguments to a function is unspecified. So it can evaluate either va_arg() expression first, which means that it could assign the wrong variadic argument to each parameter of the textType() function.

Upvotes: 4

Related Questions