Rouben Rostamian wrote:
> Does standard C provide a mechanism whereby one can reassure the
> compiler that the function f() produces no side-effects while the
> function g() has side-effects?
There's isn't a standard mechanism for doing this, although some
compilers have extensions. GCC, for example, supports so-called
"function attributes" which allow you to supply this information to
the compiler:
http://gcc.gnu.org/onlinedocs/gcc-3....n%20Attributes
(see "const" and "pure" in particular). In trivial cases, such as the
ones in your example, an optimizing compiler should be able to work
such things out by itself, but it's not always possible:
int every(int predicate(const void *),
const void *const*vals,
size_t nvals)
{
for (size_t i = 0; i < nvals; i++) {
if (!predicate(vals[i])) {
return 0;
}
}
return 1;
}
"every" itself doesn't have any side effects, but the function called
through "predicate" might; it can't be determined at compile-time in
general. If you have some way of telling the compiler that
"predicate" has no side effects then it could, in theory, do all sorts
of interesting optimizations, including memoizing both the "predicate"
and "every" functions, avoiding the overhead of calling them multiple
times with the same arguments. I doubt that any C compilers actually
do that sort of thing (unless the argument values are known at
compile-time), but it's by no means unknown in functional languages
(where side-effect free functions are more common).
Jeremy.