## Sunday, August 7, 2011

### Functional programming and GCC

I was surprised to find that its possible in GCC to specify whether a function is pure or not at compile time. A pure function is a function which has no side effects. i.e. Its output depends solely on its input arguments and it doesn't affect any other resource in the system.

GCC allows one to specify function attributes. There is a specific attribute "pure" to specify pure function. E.g.: Publish Post

int square (int) __attribute__ ((pure));
Essentially this helps in doing specific compiler optimization (common sub-expression elimination). E.g. If a piece of code calls square(2)*square(2), compiler can rewrite it in such a way that square(2) is called once and the computed value is reused in place of second call to square(2).

Functions like strlen and memcpy are very good examples of pure functions. While flose(), feof() [in a multi-threading environment], a function which may lead to an infinite loop are all examples of non-pure functions.

This is covered in detail at Function Attributes in GCC.