0

Since functions with empty parameter lists can be passed a variable number of parameters in C, Suppose I have a function defined as :

void foo(){
// I want to access the parameters passed in here
}

And I call it with arguments, say

foo(1,2,3);

Is it possible for me to get a hold of the values of those passed arguments inside my foo() function? I'm hoping for something along the lines of $_ , the default variable in Perl.

EDIT: The kind of behavior im expecting is like the one depicted in this question : C function with no parameters behavior

  • 1
    That's not how `$_` works in Perl, and I'm pretty sure that function call has undefined behavior. – melpomene Dec 02 '17 at 10:46
  • Are looking for variadic functions? – alk Dec 02 '17 at 10:50
  • The question you linked to contains this comment: "*@John it means the compiler will not check number (or type) of arguments, but you must nevertheless call the function with arguments matching the parameters in the definition.*" – melpomene Dec 02 '17 at 10:59
  • @alk yep, thats what i was looking for. – Neeraj Menon Dec 02 '17 at 11:01
  • The behavior depicted in the other question is infinite recursion (possibly with stack overflow). Please clarify what exactly you're talking about. – melpomene Dec 02 '17 at 11:05
  • @melpomene, I cited the other question only to validate that such a call will go through even though it is an obsolescent feature. My question was if it was possible to access the arguments inside the function body in such a scenario. Instead, variadic functions seems like the right way to go about this. Thanks for your responses! – Neeraj Menon Dec 02 '17 at 11:11

2 Answers2

0

C99:

6.5.2.2 Function calls

[...]

  1. If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions. If the number of arguments does not equal the number of parameters, the behavior is undefined.

(Emphasis mine.)

Thus foo(1,2,3) has undefined behavior. It's not guaranteed to even enter the function body, let alone give you access to extra arguments.

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

undefined behavior
Maybe you need Variadic Arguments

veekxt
  • 372
  • 1
  • 9