C varargs under Turbo C note: does this program compile and what does it print when characters are passed through an ellipsis?\n\n#include <stdio.h>\n#include <stdarg.h>\nvoid display(int num, ...);\n\nint main()\n{\n display(4, 'A', 'a', 'b', 'c');\n return 0;\n}\nvoid display(int num, ...)\n{\n char c; int j;\n va_list ptr;\n va_start(ptr, num);\n for (j = 1; j <= num; j++)\n {\n c = va_arg(ptr, char); /* relies on Turbo C behavior */\n printf("%c", c);\n }\n}

Difficulty: Medium

Correct Answer: No error and print A a b c

Explanation:


Introduction / Context:
This item references legacy Turbo C behavior with varargs. In standard C, arguments passed through an ellipsis undergo default promotions, meaning char and short are promoted to int. Strictly, one should therefore retrieve such values using va_arg(ptr, int). However, many old compilers (including Turbo C in common configurations) accepted retrieving as char and still produced the expected output in simple cases.


Given Data / Assumptions:

  • Compiler context is explicitly “Turbo C”.
  • Arguments are the character constants 'A', 'a', 'b', 'c'.
  • Loop prints exactly four characters, no delimiters.


Concept / Approach:
With Turbo C, retrieving the arguments as char from va_list often works because of implementation-defined calling conventions and conversions that end up truncating the promoted int back to char. While this is undefined behavior per the C standard, the question asks specifically for Turbo C outcome, which historically prints the characters as expected.


Step-by-Step Solution:
Call display(4, 'A', 'a', 'b', 'c').Loop iterates j = 1..4 and reads each character-like value.Under Turbo C, va_arg(ptr, char) yields the low byte of the promoted int, matching the intended character.Printed result → Aabc (contiguously).


Verification / Alternative check:
Portably correct code would be int x = va_arg(ptr, int); then cast to char for printing. That works across compilers and standards-compliant toolchains.


Why Other Options Are Wrong:
Unknown variable ptr and Lvalue required do not match the code. Printing a leading 4 would require explicitly printing num, which the loop does not do.


Common Pitfalls:
Assuming Turbo C behavior implies standard-conforming code. For modern, portable C, always retrieve types exactly as they are after default promotions.


Final Answer:
No error and print A a b c

More Questions from Variable Number of Arguments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion