| Ernesto Guisado's Website » Programming » C++ Programming » C++ Programming Gotchas | Articles | Miscellanea | |
I normally act as mentor for more junior developers. Most of them are new to C, to C++ or to both of them. There are lot's of things to watch out for. Here are some things that burned somebody around me. C++ is a complex language, which means I am not really sure if it's their fault. If you take a look at some C++ guidelines (see Lakos' Large Scale C++), most of them are lists of language features that you shouldn't be using.
At the bottom of the file is a list of recommendations that I derived from my experiences.
if (a >b) UpdateValues;You aren't calling the function.
UpdateValues; without
parens returns the address of the function instead of calling it.
It is equivalent to
&UpdateValues;.
while (a >b);
{
// Do something...
}
while (a =! -1)
{
// Do something...
}
char* ssn()
{
char buf[256];
strcpy(buf, "45697u");
return buf;
}
Local variables are created on the stack. After you exit a function
you shouldn't access the variable. The value you expect might have
been overwritten by a new local variable, ..., whatever. Worst
think is this might work sometimes and produces some very hard to
find errors.
Do it like this (with STL):
string ssn()
{
return "45697u";
}
I've seen a non-obvious variant of this on Win32. When creating a thread, you may specify some creation parameters (void*). If you do it like this:
for (int i = 0; i < 10; i++) CreateThread(threadFunc, &i,...);This code is trying to give a different parameter to each thread. The problem is it might work,... or not. Best create a static array with a different element for each thread and pass the address to the creation function:
static struct {
int i;
} g_ThreadParam[10];
#define ARRAY_NELEMS(a) (sizeof(a)/sizeof(a[0]))
//...
for (int i = 0; i < ARRAY_NELEMS(g_ThreadParam);i++)
CreateThread(threadFunc, &g_ThreadParam[i], ...);