MISRA Discussion Forums
Rule 0.1.9 - is zero-initialization considered "dead code"? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19)
+---- Forum: 6.0 Language independent issues (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=129)
+---- Thread: Rule 0.1.9 - is zero-initialization considered "dead code"? (/showthread.php?tid=1705)



Rule 0.1.9 - is zero-initialization considered "dead code"? - cgpzs - 25-09-2024

Consider the following example:

Code:
// third_party.h
struct Foo
{
   int32_t a;
   int32_t b;
};

// client.cpp
Foo create()
{
  Foo f{};     // Violates Rule 0.1.9?
  f.a = 123;
  f.b = 321;
  return f;
}

Does that violate Rule 0.1.9? While the initialization may be redundant, it serves a purpose as defensive programming. If we remove the zero-initialization, we risk having some members of "Foo" uninitialized, especially if we bump to a new version of "third_party.h" that adds a new member to the struct. It's safer to zero-initialize at the declaration, to ensure no members remain uninitialized.

It's also preferable to initialize like this instead of "Foo f{123, 321};", because we can see written in code which field gets which value. We need to wait until C++20 to get designated initializers in C++ to initialize everything in one line.

Thanks!


RE: Rule 0.1.9 - is zero-initialization considered "dead code"? - misra cpp - 27-09-2024

Strictly this does not violateĀ  0.1.9, because the statement that declares f cannot be removed and still leave working code, but it may be seen as zero initialising followed by assignment (i.e. the zero initialisation is redundant) which violates 0.1.6.


RE: Rule 0.1.9 - is zero-initialization considered "dead code"? - cgpzs - 27-09-2024

Thanks, it appears that my static analyzer mistakenly mapped the error message to 0.1.9.

I read now the discussion about 0.1.6:

https://forum.misra.org.uk/showthread.php?tid=1522

MISRA have previously stated that 0.1.6 is intended for DU anomalies only, so it does not appear this case falls under that category?

I also note that MISRA C++ 2023, rule 0.1.1, function f5() marks a very similar example as compliant. Is that also compliant under MISRA C++:2008?


RE: Rule 0.1.9 - is zero-initialization considered "dead code"? - misra cpp - 11-10-2024

You're right, your example should be compliant in both 2008 & 2023.

However, we think we've made a mistake in not allowing overwriting zero initialisation
This will be clarified in the next edition.