Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching variables passed to function with no arguments

Tags:

c

I don't know if it's possible but the wikipedia article here Compatibility of C and C++ says the following :

In C, a function prototype without arguments, e.g. int foo();, implies that the parameters are unspecified. Therefore, it is legal to call such a function with one or more arguments, e.g. foo(42, "hello world").

In contrast, in C++ a function prototype without arguments means that the function takes no arguments, and calling such a function with arguments is ill-formed.

In C, the correct way to declare a function that takes no arguments is by using void, as in int foo(void);.

I made the following code to test it and catch the passed variables (which doesn't work quite right)

#include<stdio.h>
#include<stdarg.h>

void foo();

int main()
{
    int i = 3;
    foo(i);
    return 0;
}

void foo()
{
//    va_list args;
//    va_start(args);
//
//    int x = va_arg (args, int);
//    printf("%d", x);
//    va_end(args);
}

Is it possible to catch the passed i or is Wikipedia talking about something completely different?

like image 607
Kartik Anand Avatar asked Oct 30 '13 08:10

Kartik Anand


1 Answers

You can't, at least not in standard C. What the Wikipedia article means is this code:

void foo();

int main()
{
    int i = 3;
    foo(i);
    return 0;
}

void foo(int i)
{
    (void)i;
}

Compiles fine in C, but it's invalid in C++ because the number of arguments don't match.

like image 115
Yu Hao Avatar answered Oct 23 '22 12:10

Yu Hao