Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC behaviour when calling a function with too many arguments

Tags:

c

gcc

I just noticed a behaviour with GCC that seems strange to me (not checked with other compilers).

If I compile this code :

#include <stdio.h>

void foo(int i)
{
  printf("Hello %d\n",i);
}

int main(){
  foo(1, 2);
  return 0;
}

I will get a compiler error :

test.c:9:5: error: too many arguments to function ‘foo’

But if I compile this code :

#include <stdio.h>

void foo()
{
  printf("Hello\n");
}

int main(){
  foo(1, 2);
  return 0;
}

I get no errors or warnings.

Could someone explain me why ?

I tested this with gcc 4.6.3 and arm-none-eabi-gcc 4.8.3

EDIT : I compile with all warnings : gcc -Wall test.c

like image 552
Quentin Avatar asked Jul 11 '14 14:07

Quentin


2 Answers

In C, writing void foo() means that foo takes an unspecified number of arguments.

To indicate that the function foo() should take no arguments, you should write void foo(void)

For this reason you should also use the signature int main(void).

like image 84
Étienne Avatar answered Nov 15 '22 03:11

Étienne


Turn on your warnings!

void foo()

is an old ANSI C way of declaring a function without a proper prototype. If you do this, the function acts sort of like void foo(...), and allows any number of arguments to be passed.

(In C++, void foo() declares a null-arity function as you'd expect).

like image 36
nneonneo Avatar answered Nov 15 '22 04:11

nneonneo