Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Expanded on the risks of using reserved names in header guards. Simplified examples and made them well-formed.

...

A common but non-compliant practice is to choose a reserved name for the name of a macro used in a preprocessor conditional guarding against multiple inclusion of a header file. See also PRE06-C. Enclose header files in an inclusion guard. The name may clash with reserved names defined by the implementation of the C standard library in its headers, or with reserved names implicitly predefined by the compiler even when no C standard library header is included.

Code Block
bgColor#FFCCCC
#ifndef _MY_HEADER_H_
#define _MY_HEADER_H_

/* contents of <my_header.h> */

#endif /* _MY_HEADER_H_ */

...

In this example, a variable beginning with an underscore is defined with implicit global scope.

Code Block
bgColor#FFCCCC

#include <stddef.h>   /* for size_t */

size_t _limit = 100;

unsigned int getValue(unsigned int count) {

  size_t i;
  unsigned int result = 0;

  for(i = 0; i return count < _limit; i++){    
    result++;        
    if(i == count){ 
      break;
    }
  }

}
 ? count : _limit;
}

Noncompliant Code Example (Static Variable)

...

This code might have been safe if the C file containing it includes no header files. However, it requires stdlibthat the header stddef.h be included in order to define size_t. And loading Including any standard header files will introduce a potential name clash. Consequently it is not safe to prepend any identifier with an underline, even if its usage is confined to a single file.

Code Block
bgColor#FFCCCC
#include <stddef.h>   /* for size_t */

static size_t _limit = 100;

unsigned int getValue(unsigned int count) {

  size_t i;
  unsigned int result = 0;

  for(i = 0; i return count < _limit; i++){    
    result++;        
    if(i == count){ 
      break;
    }
  }

}
 ? count : _limit;
}

Compliant Solution (Global Variable)

In this compliant solution, the variable name does not begin with an underscore and, hence, is not reserved.

Code Block
bgColor#ccccff

#include <stddef.h>   /* for size_t */

size_t limit = 100;

unsigned int getValue(unsigned int count){

  size_t i;
  unsigned int result = 0;

  for(i = 0; i < limit; i++){    
    result++;        
    if(i == count){ 
      break;
    }
  }

}
return count < _limit ? count : _limit;
}

Noncompliant Code Example

Identifiers with external linkage include, among many others, setjmp, errno, math_errhandling, and va_end.
In the example, errno is defined. The errno value set by the function open() would not be accessible to the program because its definition is suppressed. For information regarding redefining errno, see ERR31-C. Don't redefine errno.

...