Frage

If I have a code that look like following:

void foofunc(const int fooarg)
{
    // something here
}

Is fooarg passed by value or by reference? As fooarg is const it is not gonna get modified, so it is ok if it is passed by reference.


And if I have a code that look like following:

void foofunc(int fooarg)
{
    // something here, but fooarg is not gonna get modified
}

Will fooarg be passed by value or by reference, also will it be const or not? Situation is same as above. It is not gonna get modified.

War es hilfreich?

Lösung 4

At the language level, if you pass it by value then, of course, it is passed by value, not by reference. But how the passing is implemented physically under the hood is an implementation detail, which is not that dependent on the argument being const as it might seem at the first sight.

In many compiler implementations, "large" arguments passed by value (from the language point of view) are actually passed by reference under the hood and then a copy is made by the prologue code of the function itself. The function body uses the copy, which creates the end effect of the parameter being received by value.

In other implementations the argument is literally passed "by value", i.e. the copy is prepared in advance, by the caller.

The advantage of the former approach is that knowing the inner workings of the function, the compiler might decide not to make a copy when it knows that a copy is not needed (e.g. when the function body makes no attempts to modify the parameter value). Note that a smart compiler can perform this analysis and eliminate unnecessary copying regardless of whether the corresponding argument is declared as const.

This is a matter of optimal code generation, not governed by the language specification. However, such matters might be specified by platform-dependent ABI specs.

Andere Tipps

The declaration says it is passed by value. So it is passed by value.

It is passed by value because the declaration says it is passed by value.

It is not going to get modified, so it is OK if it is passed by reference.

No so, but otherwise. Another thread might modify the variable passed. In which case passing by reference would change the semantics.

A top-level const is ignored in function signatures, so these declarations are completlely equivalent:

void foofunc(const int fooarg);
void foofunc(int fooarg);

It follows that the semantics of both are pass-by-value. Of course, a compiler is allowed to optimize this following the "as-if" rule, so given enough information, it is allowed to use reference semantics.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top