devxlogo

Avoid Passing Arguments With Side Effects to C Runtime Library Functions

Avoid Passing Arguments With Side Effects to C Runtime Library Functions

Many of the C Runtime Library functions are in fact macros in disguise. routines, memset(), strcpy() and others are often implemented as macros that perform some low-level system call. While Standard C++ strictly forbids this macro in function disguise convention, it is still widely used in C.

You should beware of passing arguments with a side-effect to such pseudo-functions, because the results may be undefined. (A side effect is defined as a “change in the state of the execution environment.” Modifying an object, accessing a volatile object, invoking an I/O function, or calling a function that does any of these operations are all side effects.) To see the potential dangers of passing an argument with a side effect to a macro in disguise, consider the following example:

   char buff[12];  int n = 0;  /* second argument has a side-effect;  bad idea */  memset(buff, ++n, sizeof(buff);  

If memset() happens to be a macro that passes its arguments to another function, the value of n may be incremented twice before it is used.

devx-admin

Share the Post: