Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In C++, modifying an object, calling a library I/O function, accessing a volatile-qualified value, or calling a function that performs one of these actions are ways to modify the state of the execution environment. These actions are called side effects. All relationships between value computations and side effects can be described in terms of sequencing of their evaluations. The C++ Standard, [intro.execution], paragraph 13 [ISO/IEC 14882-2014], establishes three sequencing terms:

Sequenced before is an asymmetric, transitive, pair-wise relation between evaluations executed by a single thread, which induces a partial order among those evaluations. Given any two evaluations A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced. [Note: The execution of unsequenced evaluations can overlap. — end note] Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which. [Note: Indeterminately sequenced evaluations cannot overlap, but either could be executed first. — end note]

Paragraph 15 further states (nonnormative text removed for brevity) the following:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. ... The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, and they are not potentially concurrent, the behavior is undefined. ... When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. ... Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function. Several contexts in C++ cause evaluation of a function call, even though no corresponding function call syntax appears in the translation unit. ... The sequencing constraints on the execution of the called function (as described above) are features of the function calls as evaluated, whatever the syntax of the expression that calls the function might be.

Do not allow the same scalar object to appear in side effects or value computations in both halves of an unsequenced or indeterminately sequenced operation.

The following expressions have sequencing restrictions that deviate from the usual unsequenced ordering [ISO/IEC 14882-2014]:

  • In postfix ++ and -- expressions, the value computation is sequenced before the modification of the operand. ([expr.post.incr], paragraph 1)
  • In logical && expressions, if the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression. ([expr.log.and], paragraph 2)
  • In logical || expressions, if the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression. ([expr.log.or], paragraph 2)
  • In conditional ?: expressions, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression (whichever is evaluated). ([expr.cond], paragraph 1)
  • In assignment expressions (including compound assignments), the assignment is sequenced after the value computations of left and right operands and before the value computation of the assignment expression. ([expr.ass], paragraph 1)
  • In comma , expressions, every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. ([expr.comma], paragraph 1)
  • When evaluating initializer lists, the value computation and side effect associated with each initializer-clause is sequenced before every value computation and side effect associated with a subsequent initializer-clause. ([dcl.init.list], paragraph 4)
  • When a signal handler is executed as a result of a call to std::raise(), the execution of the handler is sequenced after the invocation of std::raise() and before its return. ([intro.execution], paragraph 6)
  • The completions of the destructors for all initialized objects with thread storage duration within a thread are sequenced before the initiation of the destructors of any object with static storage duration. ([basic.start.term], paragraph 1)
  • In a new-expression, initialization of an allocated object is sequenced before the value computation of the new-expression. ([expr.new], paragraph 18)
  • When a default constructor is called to initialize an element of an array and the constructor has at least one default argument, the destruction of every temporary created in a default argument is sequenced before the construction of the next array element, if any. ([class.temporary], paragraph 4)
  • The destruction of a temporary whose lifetime is not extended by being bound to a reference is sequenced before the destruction of every temporary that is constructed earlier in the same full-expression. ([class.temporary], paragraph 5)
  • Atomic memory ordering functions can explicitly determine the sequencing order for expressions. ([atomics.order] and [atomics.fences])

This rule means that statements such as

Code Block
bgColor#ccccff
langcpp
i = i + 1;
a[i] = i;

have defined behavior, and statements such as the following do not.

Code Block
bgColor#FFcccc
langcpp
// i is modified twice in the same full expression
i = ++i + 1;  

// i is read other than to determine the value to be stored
a[i++] = i;   

Not all instances of a comma in C++ code denote use of the comma operator. For example, the comma between arguments in a function call is not the comma operator. Additionally, overloaded operators behave the same as a function call, with the operands to the operator acting as arguments to a function call.

Page properties
hiddentrue

This entire rule will need to be re-evalulated for C++17, because the order of evaluation has been tightened there. For instance, the example of a[i++] = i; will now be well-defined.

See http://en.cppreference.com/w/cpp/language/eval_order, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf, and http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0400r0.html.

Noncompliant Code Example

In this noncompliant code example, i is evaluated more than once in an unsequenced manner, so the behavior of the expression is undefined.

Code Block
bgColor#FFcccc
langcpp
void f(int i, const int *b) {
  int a = i + b[++i];
  // ...
}

Compliant Solution

These examples are independent of the order of evaluation of the operands and can each be interpreted in only one way.

Code Block
bgColor#ccccff
langcpp
void f(int i, const int *b) {
  ++i;
  int a = i + b[i];
  // ...
}
Code Block
bgColor#ccccff
langcpp
void f(int i, const int *b) {
  int a = i + b[i + 1];
  ++i;
  // ...
}

Noncompliant Code Example

The call to func() in this noncompliant code example has undefined behavior because the argument expressions are unsequenced.

Code Block
bgColor#FFcccc
langcpp
extern void func(int i, int j);
 
void f(int i) {
  func(i++, i);
}

The first (left) argument expression reads the value of i (to determine the value to be stored) and then modifies i. The second (right) argument expression reads the value of i, but not to determine the value to be stored in i. This additional attempt to read the value of i has undefined behavior.

Compliant Solution

This compliant solution is appropriate when the programmer intends for both arguments to func() to be equivalent.

Evaluation of an expression may produce side effects. At specific points during execution called sequence points, all side effects of previous evaluations have completed and no side effects of subsequent evaluations have yet taken place.

The order in which operands in an expression are evaluated is unspecified in C++. The only guarantee is that they will all be completely evaluated at the next sequence point. According to ISO/IEC 14882-2003:

The following are the sequence points defined by ISO/IEC 14882-2003:

  • at the completion of evaluation of each full-expression;
  • after the evaluation of all function arguments (if any) and before execution of any expressions or statements in the function body;
  • after the copying of a returned value and before the execution of any expressions outside the function;
  • after the evaluation of the first operand of the following operators: && (logical AND); || (logical OR); ? (conditional); , (comma, but see the note immediately following);
  • after the initialization of each base and member in a class.

Note that not all instances of a comma in C++ code denote a usage of the comma operator. For example, the comma between arguments in a function call is NOT the comma operator.

According to ISO/IEC 14882-2003:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

This rule means that statements such as

Code Block
bgColor#ccccff
langcpp
i = i + 1;
a[i] = i;

are allowed, while statements like

Code Block
bgColor#FFcccc
langcpp
/* i is modified twice between sequence points */
i = ++i + 1;  

/* i is read other than to determine the value to be stored */
a[i++] = i;   

are not.

Noncompliant Code Example

Programs cannot safely rely on the order of evaluation of operands between sequence points. In this noncompliant code example, the order of evaluation of the operands to the + operator is unspecified.

Code Block
bgColor#FFcccc
langcpp
a = i + b[++i];

If i was equal to 0 before the statement, the statement may result in the following outcome:

Code Block
bgColor#FFcccc
langcpp
a = 0 + b[1];

Or it may result in the following outcome:

Code Block
bgColor#FFcccc
langcpp
a = 1 + b[1];

Compliant Solution

These examples are independent of the order of evaluation of the operands and can only be interpreted in one way.

Code Block
bgColor#ccccff
langcpp
++i;
a = i + b[i];

Or alternatively:

Code Block
bgColor#ccccff
langcpp
a = i + b[i+1];
++i;

Non-Compliant Code Example

Both of these statements violate the rule concerning sequence points stated above, so the behavior of these statements is undefined.

Code Block
bgColor#FFcccc
langcpp
i = ++i + 1;  // an attempt is made to modify the value of i twice between sequence points
a[i++] = i;   // an attempt is made to read the value of i other than to determine the value to be stored

Compliant Solution

These statements are allowed by the standard.

Code Block
bgColor#ccccff
langcpp
i = i + 1;
a[i] = i;

Noncompliant Code Example

The order of evaluation for function arguments is unspecified.

Code Block
bgColorFFcccc
langcpp
func(i++, i);

The call to func() has undefined behavior because there are no sequence points between the argument expressions. The first (left) argument expression reads the value of i (to determine the value to be stored) and then modifies i. The second (right) argument expression reads the value of i between the same pair of sequence points as the first argument, but not to determine the value to be stored in i. This additional attempt to read the value of i has undefined behavior.

Compliant Solution

This solution is appropriate when the programmer intends for both arguments to func() to be equivalent.

Code Block
bgColor#ccccff
langcpp
i++;
func(i, i);

This solution is appropriate when the programmer intends for the second argument to be one greater than the first.

Code Block
bgColor#ccccff
langcpp
j = i++;
func(j, i);

Risk Assessment

Attempting to modify an object multiple times between sequence points may cause that object to take on an unexpected value. This can lead to unexpected program behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP30-CPP

medium

probable

medium

P8

L2

Automated Detection

...

Tool

...

Version

...

Checker

...

Description

...

Compass/ROSE

...

 

...

 

...

Can detect simple violations of this rule. It needs to examine each expression and make sure that no variable is modified twice in the expression. Also no variable is modified once, and read elsewhere, with the single exception that a variable may appear on both the left and right of an assignment operator.

...

Coverity Prevent

...

EVALUATION_ORDER

...

Can detect the specific instance where Statement contains multiple side-effects on the same value with an undefined evaluation order because with different compiler flags or different compilers or platforms, the statement may behave differently.

...

ECLAIR

...

evalordr

...

Fully implemented.

...

GCC

...

 

...

Can detect violations of this rule when the -Wsequence-point flag is used.

...

Splint

...

 

...

 

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C Secure Coding Standard as EXP30-C. Do not dep

Evaluation of an expression may produce side effects. At specific points during execution called sequence points, all side effects of previous evaluations have completed and no side effects of subsequent evaluations have yet taken place.

 

The order in which operands in an expression are evaluated is unspecified in C++. The only guarantee is that they will all be completely evaluated at the next sequence point. According to ISO/IEC 14882-2003:

 

The following are the sequence points defined by ISO/IEC 14882-2003:

 

  • at the completion of evaluation of each full-expression;
  • after the evaluation of all function arguments (if any) and before execution of any expressions or statements in the function body;
  • after the copying of a returned value and before the execution of any expressions outside the function;
  • after the evaluation of the first operand of the following operators: && (logical AND); || (logical OR); ? (conditional); , (comma, but see the note immediately following);
  • after the initialization of each base and member in a class.

 

Note that not all instances of a comma in C++ code denote a usage of the comma operator. For example, the comma between arguments in a function call is NOT the comma operator.

 

According to ISO/IEC 14882-2003:

 

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

 

This rule means that statements such as

 

Code Block
bgColor#ccccff
langcpp
i =extern void func(int i, +int 1j);
a[i] = i;

 

are allowed, while statements like


 
void f(int i) {
  i++;
  func(i, i);
}

This compliant solution is appropriate when the programmer intends for the second argument to be 1 greater than the first. 

Code Block
bgColor#FFcccc#ccccff
langcpp
/*extern ivoid is modified twice between sequence points */
i = ++i + 1;  

/* i is read other than to determine the value to be stored */
a[i++] = i;   

 

are not.

 

Noncompliant Code Example

 

Programs cannot safely rely on the order of evaluation of operands between sequence points. In this noncompliant code example, the order of evaluation of the operands to the + operator is unspecified.

func(int i, int j);
 
void f(int i) {
  int j = i++;
  func(j, i);
}

Noncompliant Code Example

This noncompliant code example is similar to the previous noncompliant code example. However, instead of calling a function directly, this code calls an overloaded operator<<(). Overloaded operators are equivalent to a function call and have the same restrictions regarding the sequencing of the function call arguments. This means that the operands are not evaluated left-to-right, but are unsequenced with respect to one another. Consequently, this noncompliant code example has undefined behavior. 

Code Block
bgColor#FFcccc
langcpp
a =#include <iostream>
 
void f(int i + b[++i];

 

If i was equal to 0 before the statement, the statement may result in the following outcome:

) {
  std::cout << i++ << i << std::endl;
}

Compliant Solution

In this compliant solution, two calls are made to operator<<(), ensuring that the arguments are printed in a well-defined order. 

Code Block
bgColor#FFcccc#ccccff
langcpp
a = 0 + b[1];

 

Or it may result in the following outcome:

 

Code Block
bgColor#FFcccc
langcpp
a = 1 + b[1];

 

Compliant Solution

 

These examples are independent of the order of evaluation of the operands and can only be interpreted in one way.

 

Code Block
bgColor#ccccff
langcpp
++i;
a = i + b[i];

 

Or alternatively:

 

Code Block
bgColor#ccccff
langcpp
a = i + b[i+1];
++i;

 

Non-Compliant Code Example

 

Both of these statements violate the rule concerning sequence points stated above, so the behavior of these statements is undefined.

 

Code Block
bgColor#FFcccc
langcpp
i = ++i + 1;  // an attempt is made to modify the value of i twice between sequence points
a[i++] = i;   // an attempt is made to read the value of i other than to determine the value to be stored

 

Compliant Solution

 

These statements are allowed by the standard.

#include <iostream>
 
void f(int i) {
  std::cout << i++;
  std::cout << i << std::endl;
}

Noncompliant Code Example

The order of evaluation for function arguments is unspecified. This noncompliant code example exhibits unspecified behavior but not undefined behavior.

Code Block
bgColor#FFcccc
langcpp
extern void c(int i, int j);
int glob;
 
int a() {
  return glob + 10;
}

int b() {
  glob = 42;
  return glob;
}
 
void f() {
  c(a(), b());
}

The order in which a() and b() are called is unspecified; the only guarantee is that both a() and b() will be called before c() is called. If a() or b() rely on shared state when calculating their return value, as they do in this example, the resulting arguments passed to c() may differ between compilers or architectures.

Compliant Solution

In this compliant solution, the order of evaluation for a() and b() is fixed, and so no unspecified behavior occurs. 

Code Block
bgColor#ccccff
langcpp
i =extern void c(int i, +int 1j);
a[i] = i;

 

Noncompliant Code Example

 

The order of evaluation for function arguments is unspecified.

 

Code Block
bgColorFFcccc
langcpp
func(i++, i);

 

The call to func() has undefined behavior because there are no sequence points between the argument expressions. The first (left) argument expression reads the value of i (to determine the value to be stored) and then modifies i. The second (right) argument expression reads the value of i between the same pair of sequence points as the first argument, but not to determine the value to be stored in i. This additional attempt to read the value of i has undefined behavior.

 

Compliant Solution

 

This solution is appropriate when the programmer intends for both arguments to func() to be equivalent.

 

Code Block
bgColor#ccccff
langcpp
i++;
func(i, i);

 

This solution is appropriate when the programmer intends for the second argument to be one greater than the first.

 

Code Block
bgColor#ccccff
langcpp
j = i++;
func(j, i);

 

Risk Assessment

 

Attempting to modify an object multiple times between sequence points may cause that object to take on an unexpected value. This can lead to unexpected program behavior.

 

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP30-CPP

medium

probable

medium

P8

L2

 

Automated Detection

 

int glob;
 
int a() {
  return glob + 10;
}
 
int b() {
  glob = 42;
  return glob;
}
 
void f() {
  int a_val, b_val;
 
  a_val = a();
  b_val = b();

  c(a_val, b_val);
}

Risk Assessment

Attempting to modify an object in an unsequenced or indeterminately sequenced evaluation may cause that object to take on an unexpected value, which can lead to unexpected program behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP50-CPP

Medium

Probable

Medium

P8

L2

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

Tool

Version

Checker

Description

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC++-EXP50
Clang
Include Page
Clang_V
Clang_V
-WunsequencedCan detect simple violations of this rule where path-sensitive analysis is not required
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

LANG.STRUCT.SE.DEC
LANG.STRUCT.SE.INC

Side Effects in Expression with Decrement
Side Effects in Expression with Increment

Compass/ROSE



Can detect simple violations of this rule. It needs to examine each expression and make sure that no variable is modified twice in the expression.

Also no

 It also must check that no variable is modified once,

and

then read elsewhere, with the single exception that a variable may appear on both the left and right of an assignment operator

.

Coverity

Prevent5.0

Include Page
Coverity_V
Coverity_V

EVALUATION_ORDER

Can detect the specific instance where

Statement

a statement contains multiple side

-

effects on the same value with an undefined evaluation order because, with different compiler flags or different compilers or platforms, the statement may behave differently

.

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V
evalordr

CC2.EXP30

Fully implemented

.

GCC
Include Page
 
GCC_V
GCC_V
 


Can detect violations of this rule when the -Wsequence-point flag is used

.

Splint

3.1.1

 

 

 

 

 

 

Related Vulnerabilities

 

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

 

Other Languages

 

This rule appears in the C Secure Coding Standard as EXP30-C. Do not depend on order of evaluation between sequence points.

 

This rule appears in the Java Secure Coding Standard as EXP05-J. Do not write more than once to the same variable within an expression.

 

Bibliography

 

...

Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C++3220, C++3221, C++3222, C++3223, C++3228


Klocwork
Include Page
Klocwork_V
Klocwork_V
PORTING.VAR.EFFECTS
CERT.EXPR.PARENS
MISRA.EXPR.PARENS.INSUFFICIENT
MISRA.INCR_DECR.OTHER

LDRA tool suite
Include Page
LDRA_V
LDRA_V

35 D, 1 Q, 9 S, 134 S, 67 D, 72 D

Partially implemented

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V

CERT_CPP-EXP50-a
CERT_CPP-EXP50-b
CERT_CPP-EXP50-c
CERT_CPP-EXP50-d
CERT_CPP-EXP50-e
CERT_CPP-EXP50-f

The value of an expression shall be the same under any order of evaluation that the standard permits

...

 

 

EXP17-CPP. Treat relational and equality operators as if they were nonassociative      03. Expressions (EXP)      EXP31-CPP. Avoid side effects in assertions

end on order of evaluation between sequence points.

This rule appears in the Java Secure Coding Standard as EXP05-J. Do not write more than once to the same variable within an expression.

Bibliography


Don't write code that depends on the order of evaluation of function arguments
Don't write code that depends on the order of evaluation of function designator and function arguments
Don't write code that depends on the order of evaluation of expression that involves a function call
Between sequence points an object shall have its stored value modified at most once by the evaluation of an expression
Don't write code that depends on the order of evaluation of function calls

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: EXP50-CPPChecks for situations where expression value depends on order of evaluation (rule fully covered).
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V521, V708
SonarQube C/C++ Plugin
Include Page
SonarQube C/C++ Plugin_V
SonarQube C/C++ Plugin_V
IncAndDecMixedWithOtherOperatorsPartially implemented
Splint
Include Page
Splint_V
Splint_V



Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Bibliography

[ISO/IEC 14882-2014]Subclause 1.9, "Program Execution"
[MISRA 2008]Rule 5-0-1 (Required)


...

Image Added Image Added Image Added

[ISO/IEC 14882-2003] Sections 1.9 Program execution, 5 Expressions, 12.6.2 Initializing bases and members.
[ISO/IEC 14882-2003] Sections 1.9 Program execution, 5 Expressions, 12.6.2 Initializing bases and members.
[Summit 05] Questions 3.1, 3.2, 3.3, 3.3b, 3.7, 3.8, 3.9, 3.10a, 3.10b, 3.11.
[Lockheed Martin 05] AV Rule 204.1 The value of an expression shall be the same under any order of evaluation that the standard permits.
[Saks 07]

EXP17-CPP. Treat relational and equality operators as if they were nonassociative      03. Expressions (EXP)      EXP31-CPP. Avoid side effects in assertions