Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: 2nd NCCE based on array subscripting

...

Code Block
int globI;
double globD;

struct S {
  int i;
  
  S() : i(globI++) {}
};

struct T : S {
  double d;
  
  T() : S(), d(globD++) {}
};

Noncompliant Code Example (Pointer Arithmetic)

In this noncompliant code example, f() accepts an array of S objects as its first parameter. However, main() passes an array of T objects as the first argument to f(), which results in undefined behavior due to the pointer arithmetic used within the for loop.

Code Block
bgColor#FFCCCC
langcpp
#include <iostream>
 
// ... definitions for S, T, globI, globD ...

void f(const S *someSes, std::size_t count) { 
  for (const S *end = someSes + count; someSes != end; ++someSes) {
    std::cout << someSes->i << std::endl;
  }
}

int main() {
  T test[5];
  f(test, 5);
}

This example would still be noncompliant if the for loop had instead been written to use array subscripting, as in the following:

Noncompliant Code Example (Array Subscripting)

In this noncompliant code example, the for loop uses array subscripting. Since arry subscripts are computed using pointer arithmetic, this code also results in undefined behavior.

Code Block
bgColor#FFCCCC
langcpp
#include <iostream>
 
// ... definitions for S, T, globI, globD ...

void f(const S *someSes, std::size_t count) { 
  
Code Block
for (std::size_t i = 0; i < count; ++i) {
    std::cout << someSes[i].i << std::endl;
  }
}

int main() {
  T test[5];
  f(test, 5);
}

Compliant Solution (Array)

...