Discuss in detail the different meanings of C and C++ in function declaration

  • 2020-06-01 10:23:34
  • OfStack

1 straight think of C/C++ as medium


int func();

Such a function declaration means a function with 1 argument void(no arguments). Today, however, when I was watching C++, I suddenly saw this sentence:


 For functions with empty argument tables, C and C++ There's a big difference. in C In language, declaration 
int func2();
 Said" 1 Can take any parameter ( Any number, any type ) A function of ". This hinders type checking. And in the C++ In language it means "function with no arguments". 

The teacher did not mention this point, the school textbook did not mention it, with curiosity, I deliberately tried 1

test.c


#include <stdio.h>

void fun();
int main()
{
  fun(1, 1);

  return 0;
}

void fun(int a, int b)
{
  printf("%d\n", a+b);
}

 Compiled by 
$ gcc -Wall test.c -o test
$ ./test 2

$ mv test.c test.cpp
$ g++ -Wall test.cpp -o test
test.cpp:  The function ' int main()' In the :
test.cpp:6:10:  Error: too many arguments to function  ' void fun()'
 fun(1, 1);
 ^
test.cpp:3:6:  Note: stated herein 
 void fun();
   ^~~

And that explains why the main function is written the way it is. Right


int main(void)

Related articles: