You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C语言函数接收short类型参数?编译报错求助

函数参数用short报错、int正常的问题解决

我想传递0-200左右的小整数,所以偏好使用short类型,但将函数参数声明为short时代码无法运行;用int作为参数时程序正常,且short可作为函数返回类型。

代码示例

short Random(short lowern, short uppern) {
    // 具体实现代码
    return 23;
}

报错信息

// 错误内容:
c_temp.c:362:7: error: conflicting types for 'Random'
 short Random(short int lowern, short int uppern) {
       ^~~~~~
c_temp.c:362:1: note: an argument type that has a default promotion can't match an empty parameter name list declaration
 short Random(short int lowern, short int uppern) {
 ^~~~~
c_temp.c:5:7: note: previous declaration of 'Random' was here
 short Random();

问题原因

错误核心是函数声明与定义不匹配。你在代码第5行的short Random();是C语言的旧式函数声明,这种声明表示函数的参数列表未指定(编译器会默认认为参数调用时会被提升为int类型)。而函数定义里用了short类型参数,触发了C语言的默认参数提升规则:short、char这类小整数类型的参数,在函数调用时会自动被提升为int。

编译器看到旧式声明时,会默认参数的实际类型是int,但定义里的参数是short,两者类型冲突,因此报错。

解决方法

把函数声明改成和定义完全一致的形式即可:

// 完整参数类型声明
short Random(short lowern, short uppern);
// 或者省略参数名的标准原型声明
short Random(short, short);

这样编译器能明确参数类型,不会因为默认提升导致类型不匹配。另外,用int参数时没问题的原因是:int本身就是默认提升后的类型,旧式声明short Random();会默认参数为int,和定义里的int参数一致,因此不会报错。而short作为返回类型没问题,是因为声明里已经明确了返回值类型为short,和定义一致,不受参数提升规则影响。

内容的提问来源于stack exchange,提问作者Łegenðarý父

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 19:03:17