Main Content

AUTOSAR C++14 Rule A26-5-2

Random number engines shall not be default-initialized

Since R2020b

Description

Rule Definition

Random number engines shall not be default-initialized.

Rationale

Pseudorandom number generators depend on an initial seed value to generate a sequence of random numbers. Default initialization of random number engines is done by using a default seed, which is a constant value. If you call a random number generator that has default initialization multiple times, you get the same sequence of random numbers every time. To avoid unexpected program behavior, such as generating the same sequence of random numbers in different program executions, use unique, nondefault seed values each time that you initialize a random number generator.

An exception to this rule is allowed when you might want a deterministic sequence for consistent testing purposes.

Polyspace Implementation

The checker reports violations on the lines in which:

  • A C++ standard random number generator is default-initialized.

  • The seeding function of a random number generator is called by using an implicit call to default arguments or an explicit default_seed argument..

Note

The checker does not report random number engine initializations that have constant input arguments.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

The declaration of std::default_random_engine eng1 is noncompliant because it is constructed by using the default argument, the default_seed constant.

#include <iostream>
#include <random>

int main()
{
  std::default_random_engine eng1{};     //Noncompliant
  std::uniform_int_distribution<int> ud2{0, 100};
  std::random_device rd;
  std::default_random_engine eng2{rd()}; //Compliant
  std::default_random_engine eng3{rd()}; //Compliant
  eng3.seed();                           //Noncompliant   

return 0;
}

The second declaration std::default_random_engine eng2 is compliant because it takes a user-defined random_device object as its initialization argument.

The declaration of std::default_random_engine eng3 is also compliant. eng3.seed() is noncompliant because the seeding function std::default_random_engine seed uses the default_seed constant as an argument, which overwrites the seed of eng3 that is correctly initialized.

Check Information

Group: Algorithms library
Category: Required, Automated

Version History

Introduced in R2020b