0

Do you feel it is important to strictly use const every time the value won't be changed or pass arguments as pointers only when the data will be modified?

I'd like to do things right but if a struct passed as an argument is large in size, don't you want to be passing the address instead of copying the data? Usually it seems like just declaring the struct argument as an operand is most functional.

//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 Answers 2

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

is exactly equivalent to

v3f intersect(line_struct line1, line_struct line2);

in terms of external behavior, as both hand copies of the lines to intersect, so the original lines cannot be modified by the function. Only when you implement (rather than declare) the function with the const form, there's a difference, but not in external behavior.

These forms are distinct from

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

which doesn't have to copy the lines because it passes just pointers. This is the preferred form in C, especially for large structures. It is also required for opaque types.

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

is not valid C.

Sign up to request clarification or add additional context in comments.

3 Comments

The two first prototypes are not equivalent. In the second function you can modify your arguments in the function body.
Depending upon the compiler, applying const to pass-by-value parameters may aid optimization. The compiler should interpret the const qualifier as a statement that no writes are permitted to the parameter.
@ouah: you're right, added that they're equivalent in external behavior.
0

C has no reference (&).

In C, use a pointer to a const structure as your parameter type:

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

So only a pointer will be copied in the function call and not the whole structure.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.