What enables C to support variable function arguments (varargs), while other languages (like Java) do not support this feature? What is special in C which is not there in Java to support this?

Dani AI

Generated

asked a solid interview-style question and is right at the surface: varargs exist in C because the language and its runtime model allow them. The deeper point interviewers usually want is this — C exposes a low-level calling/argument model (the ABI/calling convention) and gives the callee a way to walk the raw argument area using va_list/va_start/va_arg. That is what makes true, unchecked variadic functions possible. See C variadic functions.

Practically that means arguments are laid out by the caller in a predictable way (stack/registers per the ABI) and the callee uses the last fixed parameter as an anchor to compute where further arguments live. That relies on default promotions and the platform calling convention, and it is not type-safe — the compiler will not verify the types of the unnamed arguments. For background on the role of calling conventions, see Calling convention.

Java, by contrast, runs on the JVM, which enforces method descriptors and type safety. There is no sanctioned way for a callee to reach into the caller stack and reinterpret raw bytes. Java 5 later added varargs syntax (Type... args), but the compiler turns that into an array parameter (type-safe sugar), not C-style raw stack walking. See Oracle’s discussion of variable arguments for details: Variable Arguments.

Concise interview answer: C can do it because its compilation model and ABIs expose raw argument layout; Java’s JVM and type system prevent that kind of unchecked access.

Recommended Answers

All 2 Replies

What exactly are you asking? What enables it? The fact that it is part of the language and someone implemented it.

What exactly are you asking? What enables it? The fact that it is part of the language and someone implemented it.

I was asked this question in an interview. The interviewer wanted to know the feature/strength/capability which is present uniquely in C (and not in Java) due to which C has the support for variable number of function arguments.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.