C Programming - Variable Number of Arguments - Discussion

Discussion Forum : Variable Number of Arguments - Point Out Errors (Q.No. 2)
2.
Point out the error if any in the following program (Turbo C).
#include<stdio.h>
#include<stdarg.h>
void display(int num, ...);

int main()
{
    display(4, 'A', 'a', 'b', 'c');
    return 0;
}
void display(int num, ...)
{
    char c; int j;
    va_list ptr;
    va_start(ptr, num);
    for(j=1; j<=num; j++)
    {
        c = va_arg(ptr, char);
        printf("%c", c);
    }
}
Error: unknown variable ptr
Error: Lvalue required for parameter
No error and print A a b c
No error and print 4 A a b c
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
15 comments Page 1 of 2.

V.Nandhini said:   6 years ago
I am not understanding it. Please, anyone, help me to get it.

Sowjanya said:   8 years ago
Please give clear explanation about this question.

Pooja said:   8 years ago
What is va_start?

Robert said:   9 years ago
Guys, watch out for some warning that will give runtime error with GCC compiler:

\Untitled1.c|13|warning: 'char' is promoted to 'int' when passed through '...'|
\\Untitled1.c|13|note: (so you should pass 'int' not 'char' to 'va_arg')|
\Untitled1.c|13|note: if this code is reached, the program will abort|

Normally the remedy for this should be to pass instead of : c = va_arg(ptr, char)

c = va_arg(ptr, int);

Arunmane said:   9 years ago
I think, it is undefined behaviour. Because in the va_arg will return character means, char can not be copied into char variable.

Example: Char c = 'A'; // this is correct way.

But in the va_arg will return char value not its ASCII, so it will be like this.

Char c = A // This is wrong. So it is undefined behaviour.

Noboby said:   1 decade ago
If I compiled thus program in C compiler, I am getting illegal instruction.

Smit Gandhi said:   1 decade ago
Q:- va_list ptr;

A:- ptr ^\' This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg.

Q:- display (4, 'A', 'a', 'b', 'c');

A:- ptr - 4.

'A', 'a', 'b', 'c' (type) ^\' This is a type name. This type name is used as the type of the expression, this macro expands to.

Q:- What is the return value of this display function?

A:- This macro returns the next additional argument as an expression of type type.

For an example :- First it start wit 'A' then 'a' and so on upto 'c'.

Aashi said:   1 decade ago
Please give explanation.

Santosh said:   1 decade ago
c = va_arg(ptr, char);

What does char indicate in this statement?

Gsurav said:   1 decade ago
Why it didn't print 4?


Post your comments here:

Your comments will be displayed after verification.