C语言,函数形参与实参个数不一致问题

​ 最近阅读工程代码的时候,同一个函数,不同场景调用时,输入的实参个数不一样,但是编译却没有问题。查看函数的定义,相关的C文件里并没有给形参指定默认值,这就很奇怪了。

​ 最终,发现在函数相关的头文件里有给形参指定默认值。这就能解释通为什么形参和实参个数不一致,编译能正常通过的问题了。下面是示例代码。

/*parainput.c 文件内容*/

#include <stdio.h> 
void sum(int a,int b,int c)
{
	int result = a + b + c;
	printf("result = %d\n",result);	
} 
/*parainput.h 文件内容*/

#ifndef _PARAINPUT_H
#define _PARAINPUT_H

void sum(int a,int b=1,int c=2);

#endif
/*main.c 文件内容*/
#include <stdio.h>
#include "parainput.h" 

void test_01(void)
{
	int a = 10;
	sum(a);
	return;
}

void test_02(void)
{
	int a = 10,b = 20;
	sum(a,b);
}

void test_03(void)
{
	int a = 10,b = 20,c = 30;
	sum(a,b,c);
}
int main(void)
{
	test_01();
	test_02();
	test_03();
	
	return 0; 
}

用G++进行编译,最终运行结果如下。

result = 13
result = 32
result = 60

--------------------------------
Process exited after 0.006126 seconds with return value 0
请按任意键继续. . .
posted @ 2022-05-09 09:03  知微之见  阅读(348)  评论(0编辑  收藏  举报