C 中的 main() 之前不能声明 void 函数

标签 c function declaration

我是 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/

相关文章:

objective-c - 回车 ("\r") 在 gdb 输出中的 C/Objective-C 中不起作用

c++ - Const C++ 函数中的赋值

javascript - 如何获取等于 10 的输入并执行在屏幕上显示“awesome”的功能

复杂声明

c - 无法破译我老师的伪代码

c - 初学者C,为什么我的字符串中添加了一堆随机的东西?

c - 实现一个程序,根据一个人的名字,打印一个人的姓名首字母

python - Python 中的 Dixon 和 Price 函数 - 将列表的元素与索引号相加

C++ - 函数范围内的函数声明?

c - c中的嵌套结构