Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: All
Dec 3, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Avoid Passing Arguments With Side Effects to C Runtime Library Functions

Many of the C Runtime Library functions are in fact macros in disguise. < stdlib.h> 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.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date