Consider, for example:
int sum(int a, int b)
{
return a + b;
}
vs.
int sum(const int a, const int b)
{
return a + b;
}
Is the second approach in general faster?
Function parameters in C are copied and sent to the function, so that changes inside the function do not affect the original values. My reasoning is that in the second sum
above, the compiler knows for sure that a
and b
are not modified inside the function, so it can just pass the original values without copying them first. That's why I think the second sum
is faster than the first. But I don't really know. In the particular simple example of sum
above, the differences, if any, should be minimal.
Edit: The sum
example is just to illustrate my point. I don't expect that in this particular example there should be large differences. But I wonder if in more complicated situations the const
modifier inside a function parameter can be exploited by the compiler to make the function faster. I doubt that the compiler can always determine whether a parameter is changed inside a function (hence my 2nd question below); hence I'd expect that when it finds a const
modifier, it does something different than when there's no const
modifier.
Question: In general, a function will be faster when its arguments are const
, than when they are not?
Question 2: In general, can a C compiler (theoretically) always determine whether a function parameter is changed inside the function?