我是 C 语言的初学者,在我的 previous question 中我曾询问过 C 语言中正确的函数声明顺序。有人告诉我,在标准 C 语言中,有必要在调用函数之前先声明函数。
但是对于以下示例代码,我无法在 main() 之前声明函数 times2p。我试图将其声明为: void times2(int in_data); 就在 main() 之前,但出现错误。下面是示例代码:
#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)) ===|
最佳答案
您当前版本问题中的代码不正确,但并非出于您所询问的原因。
main
之前的 void
函数声明没有任何问题,编译器也不会提示它们。问题是 void
函数不返回值,而您尝试像它们返回值一样调用它们:
int s = times2(y);
仅当 times2(y)
返回 int
值(或隐式可转换为 int
的某种类型的值)时,这才是正确的.
另外,看看函数的定义:
void times2(int in_data){
in_data = in_data*2;
}
参数in_data
是函数内的局部变量。有效地更改其值没有任何作用。
您的 times2p
函数看起来不错,应该可以工作。如果您希望 times2() 有用,它需要返回一个值:
int times2((int in_data) {
return in_data * 2;
}
关于C 中的 main() 之前不能声明 void 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59328980/