GCC behavior when calling a function with too many arguments

I just noticed GCC behavior that seems strange to me (not tested by 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 functionfoo

But if I compile this code:

#include <stdio.h>

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

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

I have no errors or warnings.

Can someone explain to me why?

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

EDIT: I am compiling all warnings: gcc -Wall test.c

+4
source share
3 answers

In C, the notation void foo()means that foo takes an indefinite number of arguments.

To indicate that the function foo()should not accept any arguments, you should writevoid foo(void)

int main(void).

+6

!

void foo()

- ANSI C . , void foo(...) .

( ++ void foo() , ).

+2

, gcc . Étienne , f extern, , (6.7.6.3§14 C11, 6.7.5.3§14 C99), ( ):

. , , , . , , .

clang (v3.4) (too many arguments in call to 'foo') , ( ) :

foo.c:

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

bar.c:

#include <stdio.h>
void foo (int x, int y, int z) { printf("Hello %d\n", z); }

:

$ clang -o foo bar.c foo.c
$ ./foo
Hello 1405669720
+2

Source: https://habr.com/ru/post/1548079/


All Articles