There is no standard way of doing so, but some compilers have annotations that you can use to that effect, for example, in GCC you can use the __attribute_pure__
tag in a function (alternatively __attribute__((pure))
) to tell the compiler that the function is pure (i.e. has no side effects). That is used in the standard C library extensively, so that for example:
char * str = get_some_string();
for ( int i = 0; i < strlen( str ); ++i ) {
str[i] = toupper(str[i]);
}
Can be optimized by the compiler into:
char * str = get_some_string();
int __length = strlen( str );
for ( int i = 0; i < __length; ++ i ) {
str[i] = toupper(str[i]);
}
The function is declared in the string.h header as:
extern size_t strlen (__const char *__s)
__THROW __attribute_pure__ __nonnull ((1));
Where __THROW
is a no throw exception in case that it is a C++ compiler parsing the function, and __nonnull((1))
tells the compiler that the first argument should not be null (i.e. trigger a warning if the argument is null and -Wnonnull flag is used).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…