Pure functions in C++

Declare a function to be side-effect free

Dec 18, 2018 · 2 min read
Image for post
Image for post

C++ is not a functional programming language. Functions causing side-effects are the norm with functions routinely modifying member variables. If a compiler does not see the body of a function, it assumes that the function causes side effects. This can result in missed optimization opportunities.

A missed opportunity for optimization

Consider the following code. Here the main function (for some reason) computes the square of the total number of arguments twice and returns the sum of the squares.

Here the compiler does not see the body for the square function so it assumes that the function can cause side effects. The following assembly code shows two calls to the add function.

The compiler could not optimize away the second call, as it cannot assume that the square function does not have side effects.

Optimization with the pure function attribute

If there was a way to tell the compiler that a function is pure (i.e. no side-effects), the compiler could use this information to optimize the code.

If we just add the [[gnu::pure]] attribute to the square function, the compiler will assume that the function does not cause side effects.

When a function is declared pure, the compiler will also ensure that:

  • The function does not access or update any global variables.
  • The return value of the function just depends upon the input parameters.

This results in a significant optimization and the compiler can just call the square function once and just double the result — add eax, eax. The pure declaration guarantees that multiple calls to the function with the same parameters will always result in the same return value.

At the time of this writing, the [[gnu::pure]] attribute is supported by GCC and Clang compilers.

Learn more

Jason Turner’s C++ weekly video that forms the basis of this post.

Compiler explorer links for the example presented above:

Software Design

Architecture | Design | Coding

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store