为什么在头文件的函数声明中,对于通过值传递的参数而言,const是不必要的? [英] Why is const unnecessary in function declarations in header files for parameters passed by value?

查看:348
本文介绍了为什么在头文件的函数声明中,对于通过值传递的参数而言,const是不必要的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在阅读有关const关键字在C中用作函数参数的信息,以及

I was recently reading about the usage of const keyword as function arguments in C and the way to use that has been mentioned in When and for what purposes should the const keyword be used in C for variables and been accepted as correct answer. In this post, one point mentions that

切勿在函数原型中使用const来传递参数 价值.它没有任何意义,因此只是噪音".

Never use const in a function prototype for a parameter passed by value. It has no meaning and is hence just 'noise'.

我使用这种方式,它对我有用,但是我不确定为什么这对于按值传递的参数来说是噪声而对按引用传递的参数来说不是噪声(更合适的是指针) C中的值,因为C中没有pass by valuepass by reference的概念).因此,通过这种解释,当我将指针作为函数参数传递并使用const关键字时;我必须对头文件中的声明和C文件中的定义都执行此操作,但是我不必在声明(头文件)中的非指针参数中使用const关键字,而仅在定义C文件中的功能.

I used this way and it works for me but I am not sure why that is a noise for parameters passed by value and yet not a noise for the parameters passed by reference (more aptly the pointer values in C as there is not concept of pass by value and pass by reference in C). So, by this explanation when I pass a pointer as a function argument and use a const keyword; I have to do this for both the declaration in the header file and the definition in the C file but I need not use the const keyword for a non-pointer argument in the declaration (header file) and only use it while defining the function in the C file.

有什么解释吗?

推荐答案

您引用的语句有点误导,因为在C语言中,所有参数都是按值传递的. * 我想它正在尝试区分自变量本身,并且对于作为指针的自变量特殊情况,是指称对象.

The statement you quote is a bit misleading, because in C, all arguments are passed by value.* I suppose it is trying to distinguish between the arguments themselves and, for the special case of arguments that are pointers, their referents.

无论如何,关键是要在函数声明中限定const的函数参数不向调用者传递任何信息.无论采用哪种限定条件,该函数都无法修改任何参数的调用方副本,因为参数会被传递值.

In any event, the point is that const-qualifying a function parameter in the function declaration conveys no information whatever to callers. Regardless of such qualification, the function cannot modify the caller's copy of any argument anyway, because arguments are passed by value.

* 但是,请注意,数组根本不会传递.在大多数情况下,在函数调用表达式中,数组值衰减"到指针,并且这些指针按值传递.产生的效果与通过引用传递数组时的效果类似但不完全相同.

*Note, however, that arrays are never passed at all. In function call expressions, as in most contexts, array values "decay" to pointers, and those pointers are passed by value. This produces an effect similar, but not identical, to what you would have if arrays were passed by reference.

这篇关于为什么在头文件的函数声明中,对于通过值传递的参数而言,const是不必要的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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