Const correctness

It is a programming principle that emphasizes the proper use of the const qualifier to enforce immutability . It involves applying the const keyword in a consistent and meaningful way to variables, function parameters, and pointers.

In C (and C++), the const keyword is used to declare that a variable is read-only and should not be modified. When applied to function parameters, it indicates that the function will not modify the passed arguments.

?

Const correctness brings several benefits to software development:

?

  1. Preventing accidental modifications: By marking variables, parameters as const, you explicitly state the read only permissions. This helps to catch accidental modifications at compile-time and ensures that the intended behavior of read-only data is maintained.
  2. Enhancing code readability: Const correctness serves as documentation for the code, making it easier for other developers to understand how variables are intended to be used. It clarifies which parts of the code are responsible for modifying data and which parts are not.
  3. Enabling code optimization: The const qualifier provides hints to the compiler that certain optimizations can be applied. It allows the compiler to make assumptions about the immutability of data, might lead to performance improvements.

?

In summary: use a "constant" qualifier whenever the buffers are read only and not intended to be written. One common example is to passing data by address where the called routine is not allowed to change the data.

?

/*where bar pointed data is read only in scope of foo!*/
void foo(const uint32 * bar, uin8 size);

?

#SoftwareDevelopment?#DefensiveTechniques?#misra?#QualityCoding?#BugPrevention?#CodeSecurity?#bug?#defects?#code #codequality #programming?

要查看或添加评论,请登录

Sarea Alhariri的更多文章

  • Stack Smashing Protection

    Stack Smashing Protection

    This material is always incomplete, and might contain errors. So, I am always ready to accept constructive feedback on…

  • Object Oriented Programming Paradigm I

    Object Oriented Programming Paradigm I

    Every Thing is an object & Every object has attributes and behaviors. This was the first sentence I heard when started…

    2 条评论

社区洞察

其他会员也浏览了