Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by const reference in C

Does C support pass by const reference like C++? If not, are there other ways to make pass-by-value more efficient? I don't think it makes sense to pass references to a function only because it's more efficient.

like image 977
Milad Avatar asked Oct 09 '13 15:10

Milad


People also ask

What is pass by const reference?

Passing By Reference To Const in C++ Passing By Reference To Const in C++ C++ is an example of a message-passing paradigm language, which means that objects and values are passed to functions, which then return further objects and values based on the input data.

What is the difference between pass-by-reference and pass by const reference?

From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified.

What is the purpose of pass-by-reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in.

What is call by constant reference?

call by value will copy all the elements of the object it does protect the callers argument because if you are going to change something it is only a copy you are changing. calling by const reference does not copy elements but because of the "const" it will protect caller's argument. You const reference.


1 Answers

C does not support references or passing by reference. You should use pointers instead and pass by address. Pass-by-value is efficient for primitive types, but does a shallow copy for structs.

In C++ it makes a LOT of sense to pass objects by reference for efficiency. It can save a ton of copying and calling of constructors/destructors when copy constructors are defined. For large data objects (such as std::list) it is impractical to pass-by-value because the list would be copied when passed. Here you should definitely pass by reference.

like image 174
edtheprogrammerguy Avatar answered Sep 21 '22 05:09

edtheprogrammerguy