The restrict keyword in C programming

The restrict keyword tells the compiler that for the lifetime of the respective pointer you will access the object pointed to only through this pointer (and pointers derived from it by means of pointer arithmetics). This helps the compiler to generate optimized code as demonstrated in the Wikipedia page on ‘restrict’.

In the descriptions of restrict, you will usually read the wording ‘you intend to access …’. However, as far as I understood, the result is undefined if you violate this intention. This is well described in the article ‘Demystifying The Restrict Keyword’ by Mike Acton. Background information on strict aliasing can be found in the article ‘Understanding Strict Aliasing’ by the same author.

restrict was introduced in the C99 standard (C99 on Wikipedia). Regarding GCC restrict was implemented since version 3.0 (or 3.1… doesn’t really matter anymore, I guess) but it makes good use of its optimization potential since 4.5. In GCC you can make use of restrict also if you do not (or do not want to) use -std=c99. This requires using the syntax __restrict__ (apparently __restrict works as well).

It is implemented in the Intel C compiler, where you need to pass any of the options /Qrestrict (-restrict) or /Qc99 (-c99) (see also this).

The MS compiler does not support C99, however, since version 2010 of MSVC it supports restrict using the syntax __restrict.

Most importantly, restrict can make large differences regarding code run time!

Leave a Reply