C Programming - Variable Number of Arguments - Discussion

Discussion Forum : Variable Number of Arguments - Point Out Errors (Q.No. 5)
5.
Point out the error in the following program.
#include<stdio.h>
#include<stdarg.h>

int main()
{
    void display(int num, ...);
    display(4, 12.5, 13.5, 14.5, 44.3);
    return 0;
}
void display(int num, ...)
{
    float c; int j;
    va_list ptr;
    va_start(ptr, num);
    for(j=1; j<=num; j++)
    {
        c = va_arg(ptr, float);
        printf("%f", c);
    }
}
Error: invalid va_list declaration
Error: var c data type mismatch
No error
No error and Nothing will print
Answer: Option
Explanation:
Use double instead of float in float c;
Discussion:
6 comments Page 1 of 1.

Amrendra said:   8 years ago
'float' is promoted to 'double' when passed through '...'.

So it needs to use double in va_arg.

Mohit chauhan said:   1 decade ago
display(4, 12.5, 13.5, 14.5, 44.3) in this function all parameter are double by default. They can't be treated as float. So in va_arg(ptr, float)we have to pass double in place of float. It will work.

Swarna sharma said:   1 decade ago
Here why we need to take the variable c as double? We are assigning the value returned by the function var_arg(), the definition of that function is not there in the program.

Nandhini Krishnan said:   1 decade ago
@Nayak: In the variable-length part of a variable-length argument list, the "default argument promotions'' apply: types char and short int are promoted to int, and float is promoted to double. Therefore, printf's %f format always sees a double.

Nandhini Krishnan said:   1 decade ago
Why shouldn't i use float??? Why is it showing illegal instruction if i use float???

Nayak said:   1 decade ago
For what ? It is showing illegal instruction.

Post your comments here:

Your comments will be displayed after verification.