正确的参数为const或操作数

时间:2012-02-23 21:33:49

标签: c struct arguments const operands

您认为每次不更改值时严格使用const或仅在修改数据时将参数作为指针传递是否很重要?

我想做正确的事情,但如果作为参数传递的struct大小很大,你不想传递地址而不是复制数据吗?通常,似乎只是将struct参数声明为操作数最有效。

//line1 and line2 unchanged in intersect function
v3f intersect( const line_struct line1, const line_struct line2); 
//"right" method?  Would prefer this:
v3f intersect2( line_struct &line1, line_struct &line2); 

2 个答案:

答案 0 :(得分:1)

v3f intersect( const line_struct line1, const line_struct line2);

完全等同于

v3f intersect(line_struct line1, line_struct line2);

就外部行为而言,由于两行的副本都复制到intersect,因此原始行不能被函数修改。只有当你实现(而不是声明)具有const形式的函数时,才会有区别,但不会出现外部行为。

这些形式与

不同
v3f intersect(const line_struct *line1, const line_struct *line2);

不必复制行,因为它只传递指针。这是C中的首选形式,特别是对于大型结构。 opaque types也需要它。

v3f intersect2(line_struct &line1, line_struct &line2);

无效C.

答案 1 :(得分:0)

C没有参考(&)。

在C中,使用指向const结构的指针作为参数类型:

v3f intersect(const line_struct *line1, const line_struct *line2);

因此,只有一个指针将被复制到函数调用中而不是整个结构中。