【发布时间】:2020-04-07 06:50:06
【问题描述】:
我是 C 语言的初学者,在我的 previous question 中,我询问了 C 中正确的函数声明顺序。有人告诉我,在标准 C 中,有必要在调用函数之前声明函数。
但是对于下面的示例代码,我不能在 main() 之前声明函数 times2p。我试图在 main() 之前将其声明为:void times2(int in_data);,但出现错误。下面是示例代码:
#include <stdio.h>
#include <stdlib.h>
void times2p(int *in_data);
void times2(int in_data);
int main()
{
int y = 5;
int s = times2(y);
printf("%d\n", y);
printf("%d\n", s);
printf("-------------\n");
int yp = 5;
times2p(&yp);
printf("%d\n", yp);
return 0;
}
//Multiplies the input argument by two
void times2(int in_data){
in_data = in_data*2;
}
void times2p(int *in_data){
*in_data = *in_data*2;
}
在这种情况下应该如何以及在哪里声明 times2p 函数?如果我不声明代码仍然编译没有错误,但我被告知我必须在上一个问题中声明 C 中的函数。
这是错误:
||=== Build: Debug in test1 (compiler: GNU GCC Compiler) ===|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c||In function 'main':|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c|16|error: void value not ignored as it ought to be|
C:\Users\nnn\Documents\CodeBlocks\test1\main.c|13|warning: unused variable 'read_x' [-Wunused-variable]|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
【问题讨论】:
-
是因为您应该将其声明为
void times2p(int *in_data);以匹配函数定义吗?缺少*。 -
那些错误是什么?
-
如果你不声明函数,你编辑了代码“编译没有错误”。不过应该有警告吗?
-
请显示您遇到的确切错误。
-
一个 void 函数不返回任何值。这就是问题所在:int s = times2(y);
标签: c function declaration