3

Is it possible to declare a function as pure or const (using the GCC attributes),

With return arguments ? (where an argument is used for a return value).

For example:

void mid_v3_v3v3(float r_out[3], v0[3], v1[3])
{
    r_out[0] = (v0[0] + v1[0]) * 0.5f;
    r_out[1] = (v0[1] + v1[1]) * 0.5f;
    r_out[2] = (v0[2] + v1[2]) * 0.5f;
}

With the exception of r_out, this function is const, is there some way to tag an argument as a return value, but otherwise treat the function as const?

see: https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Function-Attributes.html

1 Answer 1

1

Your own link partly answers the question. Regarding const:

Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.

Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void.

The documentation for pure is actually wrong and self-contradictory; it says the function can only access its parameters and/or global variables, but then gives strlen (which accesses the member pointed to by its parameter) as an example.

Anyway, for your "return arguments" usage, I don't think either of these approaches is viable. What you could do, however, is use a function returning a structure containing the results array; then the pure attribute should apply (assuming the examples, and not the text, for pure are correct).

Sign up to request clarification or add additional context in comments.

2 Comments

The documentation could be clearer but I don't think it's contradictory. It doesn't say that it can only access parameters and global variables, it says "their return value depends only on the parameters and/or global variables", in contrast to "those depending on volatile memory or other system resource, that may change between two consecutive calls". Combined with the no side effects rule, this means the return value of the function is the same given the same arguments unless you change something in between the calls.
strlen depends on something other than parameters or global variables; it depends on the object pointed to by the parameter. This distinction is very important, to the point that the above cited text on const emphasizes it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.