uniquenamehere
uniquenamehere

Reputation: 1949

Pass by const pointer vs. pass by value for built in types. Efficiency

I almost only find C++ posts and not C, when I try to find an answer for this.

For built in types as int, char etc. is there any performance difference between pass-by-value and by const pointers?

Is it still good programming practice to use the const keyword when passing-by-value?

int PassByValue(int value)
{
    return value / 2;
}

int ConstPointer(const int * value)
{
    return (*value) / 2;
}

Upvotes: 1

Views: 360

Answers (3)

Jonas Bötel
Jonas Bötel

Reputation: 4482

Pass by const pointer is never faster than by value as long as the value is less or equal the size of a pointer (sizeof). It also is more annoying and sometimes even wrong (stack variables).

Upvotes: 2

igleyy
igleyy

Reputation: 605

Passing built-in types like int, char by pointer does not result in better performance results.

Using const keyword passing-by-value does not matter since original value won't be changed.

Upvotes: 1

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

In general the pass by value should be faster. In fact the value might have been already in the registers, in which case would not be necessary to access the cache. However if the function code is compiled together with the caller code, it is possible that the compiler will optimize anyway.

Upvotes: 1

Related Questions