Vince
Vince

Reputation: 4439

C programming: the cost of passing by value

I am learning C and get confused about something I read online.

At http://www.cs.bu.edu/teaching/c/stack/array/

I could read:

Let's look at the functions that determine emptiness and fullness. Now, it's not necessary to pass a stack by reference to these functions, since they do not change the stack. So, we could prototype them as:

int StackIsEmpty(stackT stack);
int StackIsFull(stackT stack);

However, then some of the stack functions would take pointers (e.g., we need them for StackInit(), etc.) and some would not. It is more consistent to just pass stacks by reference (with a pointer) all the time

(I am not showing the code for what a stackT is, it is just a dynamic array)

From my (maybe limited) understanding, the disadvantage of passing by value is that the data is duplicated in the stack memory of the function. Since a stackT might be big, passing by value rather than pointer would be time consuming.

Do I get it right or am I still not clear with the basics ?

Upvotes: 1

Views: 169

Answers (2)

Zach Stark
Zach Stark

Reputation: 575

You are correct. Passing by value causes the program to copy, in the entirety, all of the data in that parameter. If it's only one or two ints, no problem, but copying multiple kilobytes is very expensive. Passing by reference only copies the pointer.
However, you must watch out for changing the data pointed at by the pointer and then expecting to return to it unchanged. C++ has passing by "const reference", which is like a guarantee that the data will not be changed, but C does not.

Upvotes: 1

Eric J.
Eric J.

Reputation: 150138

Correct, if you pass something "large" by value that item is copied onto the stack.

Passing a pointer to the data avoids the copy.

It is doubtful that the performance difference will be meaningful in most real-world applications, unless "large" is actually "huge" (which in turn may overflow the stack).

Upvotes: 3

Related Questions