函数原型和块代码中的变量声明:有区别吗? [英] Variable declaration in function prototype and in block code : difference?

查看:94
本文介绍了函数原型和块代码中的变量声明:有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 int array [] 在main而不是在函数原型中引发编译错误?
是否应该始终在函数原型中编写 int *数组更好?

Why int array[] raise a compilation error in main but not in function prototype ? Should it mean that it is better to always write int * array in function prototype ?

void myfoo (int array[]) { // No compilation error
;}

void myfoo1 (int *array1) { // No compilation error
;}

int main() {
    int array[]; // Compilation error
    int* array1; // No compilation error
}


推荐答案

main 的块内的数组声明需要一个大小,而function参数中的数组声明不需要的原因是 main 定义数组,而function参数仅仅是接收其他定义的数组。

Fundamentally, the reason an array declaration inside the block for main needs a size and the array declaration in the function parameter does not is that the declaration in main is defining an array, whereas the function parameter is merely receiving an array that something else defines.

因此 main 中的定义需要一个大小,因为它必须为数组保留存储空间。

So the definition in main needs a size because it must reserve storage for the array.

函数参数仅接收数组,因此只需要知道数组从哪里开始。它不需要知道大小。 (也就是说,编译器不需要知道大小即可编译代码。该函数可能需要知道大小即可执行其预期目的,但这对程序员而言,而不是编译器要紧。)

The function parameter is merely receiving an array, so it only needs to know where the array starts. It does not need to know the size. (That is, the compiler does not need to know the size in order to compile the code. The function may need to know the size in order to perform its intended purpose, but that is a matter for the programmer, not the compiler.)

由于C规则,数组实际上不能作为函数参数传递。只要将数组作为函数参数给出,编译器就会自动将其转换为指向其第一个元素的指针。同样,函数参数可以是指针,但实际上不能是数组。当您将函数参数声明为数组时,编译器会自动对其进行调整以声明一个指针。因此,函数声明 void myfoo(int array [])会自动调整为 void myfoo(int * array)

Due to C rules, arrays can never actually be passed as function arguments. Whenever an array is given as a function parameter, the compiler automatically converts it to a pointer to its first element. Similarly, a function parameter can be a pointer but cannot actually be an array. When you declare a function parameter as an array, the compiler automatically adjust it to declare a pointer instead. So the function declaration void myfoo(int array[]) is automatically adjusted to be void myfoo(int *array).

需要在 main 中声明的大小的特定规则为C 2018 6.7 7:

The specific rule that requires the declaration in main to have a size is C 2018 6.7 7:


如果声明的对象标识符没有链接,则该对象的类型应在其声明者的末尾或在如果它具有初始化程序,则返回其init-declarator的末尾;…

If an identifier for an object is declared with no linkage, the type for the object shall be complete by the end of its declarator, or by the end of its init-declarator if it has an initializer;…

这篇关于函数原型和块代码中的变量声明:有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆