The C Standard (ISO/IEC 9899:2011 aka C11) generally permits compilers to optimize away inter alia unreachable/infeasible code. While this is generally an acceptable behaviour, there are times (especially with respect to defensive coding) when this is not desireable.
Proposal N2165 introduces the concept of attributes, denoted by [[2258]], and has been accepted for inclusion into C2x.
This proposal builds on N2165, to introduce the [[defensive]] attribute.
Defensive coding provides a means of detecting, and acting upon, conditions and states that (under normal operation) should not occur. Should such defensive coding be removed by the compiler, then (in the event that abnormal operation occurs) then this may not be detected or dealth with.
This proposal has a secondary benefit that provides a mechanism for informing a Static Analyser that unreachable code is intentionally unreachable.
The [[defensive]] attribute may be used on:
Where the [[defensive]] attribute is used, the following statement (or compound statement) shall not be optimized away, even if statically unreachable/infeasible.
enum { STATE_START=0, STATE_RUN } state = STATE_START;
// Example of use-case with ELSE
if ( state == STATE_START ) { do_start(); }
else if ( state == STATE_RUN ) { do_run(); }
else [[defensive]]
{
// Strictly speaking, unreachable
// ... without attribute, could be removed by compiler
state = STATE_START; // Trigger restart
// Example of use-case with SWITCH
switch ( state )
{
case STATE_START: { do_start(); break; }
case STATE_RUN: { do_run(); break; }
default [[defensive]]
{
// Strictly speaking, unreachable
// ... without attribute, could be removed by compiler
state = STATE_START; // Trigger restart
break;
}
}
N2165 (Attributes in C) - http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2165.pdf