0

When I using variable parameters, it works well with int and double, but when it comes to float, error happens.

Here is the code.

void vaParamTest(int a, ...)
{
    va_list ap;
    va_start(ap, a);
    for (int  i = 0; i < a; i++)
        printf("%f\t", va_arg(ap, float));
    putchar('\n');
    va_end(ap);
}

I pass parameters like this.

vaParamTest(3, 3.5f, 8.3f, 5.1f);
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
Robert
  • 13
  • 2
  • 1
    That makes no sense whatsoever. But what error message are you getting? What output? I mean, you are getting something, right? – ATaylor Sep 11 '12 at 05:40
  • You might want to explain a bot more about what "error happens"... Compilation error? Runtime error? Output not what expected? I suspect the last, as `3` (the first argument) is not a float. – Some programmer dude Sep 11 '12 at 05:43

1 Answers1

10

Variables that are passes as variadic function arguments are default-promoted, which makes all floats into doubles. You can never have a float argument (just like you can never have a char argument). In printf, %f always means double.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Thank you so much for your help, but now I'm even more confused. I find this paragraph [6.5.2.2] in your link. Obviously, there is no question for the description of integer promotions. When pass char s to a function, for example, void paramStack(char x, char y, char z), all char s is 4 Bytes. However, for double promotions, void paramStack(float x, float y, float z), all floats take 4 Bytes, not 8 bytes like double. I can find like this, &x: 0x0040fe10 &y: 0x0040fe14 &z: 0x0040fe18 Do double promotions happens in this function? – Robert Sep 11 '12 at 07:20
  • @Robert - No, this is all about the `...` part. Rules are different there, because the compiler doesn't know the intended types. – Bo Persson Sep 11 '12 at 07:24
  • @Bo Persson- Thank you. The **double promotions** only happens when there is no parameter for a given argument, but for an ordinary function call, another rule works, Is that right? – Robert Sep 11 '12 at 08:01
  • @Robert - Yes, when the parameter type is known, the argument is promoted to that type (if needed). The `...` is special, so it has special rules. – Bo Persson Sep 11 '12 at 08:27
  • @Robert: There are certain times when a value is default-promoted. Being a variadic argument (i.e. matching the ellipsis) is such a time. Default-promotion entails that float values are converted to and passed as doubles. An ordinary, prototyped function like `void f(char, float, short);` still works as expected! (The linked question focuses on integral default promotions, so the part about float-to-double may not be mentioned there, though it's nearby in the standards.) – Kerrek SB Sep 11 '12 at 09:37