5

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.

This isn't my real name
  • 4,869
  • 3
  • 17
  • 30
Milad
  • 4,901
  • 5
  • 32
  • 43
  • In C, use pointers, you will copy only the pointer. `I don't think it makes sense to pass references to a function only because it's more efficient` -> This is very dangerous in C++. If you don't pass a reference, you do an implicit copy. This is very costly and that's why it is recommended to have private copy-constructor. – Arnaud Denoyelle Oct 09 '13 at 16:07
  • The benefit of reference variable is simple to use capable as pointers! – Grijesh Chauhan Oct 09 '13 at 16:14

1 Answers1

9

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.

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
  • I would like to clarify then; if I want to pass a struct quickly in C, I should pass by pointer, and use the const keyword if I didn't intend on modifying? – DeepDeadpool Jul 09 '15 at 15:58