Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Modifications based on feedback from Robert.

...

The following type definition improves readability at the expense of introducing a const-correctness issue.  In this example, the const qualifier applies to the typedef itself instead of applying to the underlying object type.  So func does not take a pointer to a const struct obj, but is instead taking a const pointer to a struct obj.

Code Block
bgColor#FFcccc
langc
struct obj {
  int i;
  float f;
};
typedef struct obj *ObjectPtr;
 
void func(const ObjectPtr o); {
  /* Can actually modify o's contents, against expectations. */
}

Compliant Solution

This compliant solution makes use of type definitions, but does not declare a pointer type and so cannot be used in a const-incorrect manner.

Code Block
bgColor#ccccff
langc
struct obj {
  int i;
  float f;
};
typedef struct obj Object;
 
void func(const Object *o);

...

 {
  /* Cannot modify o's contents. */
}

Noncompliant Code Example (Windows)

...

Code Block
bgColor#FFcccc
langc
#include <Windows.h>
 
void func(const LPSTR str) {
  /* Use,Can butmutate do not mutate, strstr's contents, against expectations. */
}

Compliant Solution (Windows)

The compliant solution demonstrates a common naming convention found in the Win32 APIs to utilize , using the proper const type.

Code Block
bgColor#ccccff
langc
#include <Windows.h>
 
void func(LPCSTR str) {
  /* Use,Cannot butmodify do not mutate, str str's contents. */
}

Noncompliant Code Example (Windows) 

...

Code Block
bgColor#FFcccc
langc
#include <Windows.h>
 
void func(const LPPOINT pt) {
  /* Can modify pt's contents, against expectations. */
}

Compliant Code Example (Windows)

Code Block
bgColor#ccccff
langc
#include <Windows.h>
 
typedef const POINT *LPCPOINT;
void func(LPCPOINT pt) {
  /* Cannot modify pt's contents. */
}

Exceptions

Function pointer types are an exception to this recommendation. 

...