Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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>
/* typedef char *LPSTR; */
 
void func(const LPSTR str) {
  /* Can mutate str's contents, against expectations. */
}

Compliant Solution (Windows)

...

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

Noncompliant Code Example (Windows) 

...

Code Block
bgColor#FFcccc
langc
#include <Windows.h>
/*
  typedef struct tagPOINT {
    long x, y;
  } POINT, *LPPOINT;
*/
 
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 struct tagPOINT {
    long x, y;
  } POINT, *LPPOINT;
*/
 
typedef const POINT *LPCPOINT;
void func(LPCPOINT pt) {
  /* Cannot modify pt's contents. */
}

Exceptions

Function pointer types are an exception to this recommendation. 

...