if
or
while
statement, for example
if (x > 0); { x++; foo(x); }will result in always executing the block following the
if
.
Something similar can be said for while
statements.
if (x = 0)
instead of if (x == 0)
. When compiled
with g++ -Wall
, this construction will result in a warning: 'suggest
parentheses around assignment used as truth value'. The same goes for
while
.
if (mask & 0x80 == 0)
looks ok, but it is not, because ==
has a higher precedence than &
. This construct is in fact equivalent
to if (mask & (0x80 == 0))
and will always be false (left as an
exercise for the reader). The obvious solution to this problem is to use
parentheses around (complex) expressions before and after the ==
as
in if ((mask & 0x80) == 0)
.
break
at the end of a case-statement; a switch
such
as
switch(value) { case 0: printf("value = 0\n"); case 1: printf("value = 1\n"); default: printf("value is not 0 or 1\n"); }will, when
value
equals 0, produce
value = 0 value = 1 value is not 0 or 1instead of the 'expected' output
value = 0The compiler will not generate a warning for this, since it's perfectly legal.
&&
, ||
) and the bitwise
operators (&
, |
).
printf("debug: x = %d\n");
. This will result in some random value
printed out (depending on the contents of the stack).
Fortunately, when compiling with
-Wall
, gcc will warn you: test.cc:5: warning: too few arguments for format
.
if (function_name)
instead of
if (function_name())
. The first is also legal in C/C++ and will not
generate any errors or warnings.
int foo(int x) { int x2, y; x2 = x * 3.1415; /* we're doing some y = x2 * x + x * x + 1.1; pretty extensive x = abs(x2) > 1 ? 0 : 1; calculations here */ return y * x; }This looks very nicely formatted, but it won't return the correct result. It's much safer to always begin and end a comment on the same line, or use the
//
when programming in C++.
int intarray[10];
is an array that ranges from 0 to 9, not from 1 to
10. Accessing the 10th element when there is none can result in
unpredictable behaviour, depending on the variables stored in memory that
are immediately following that array. Possible behaviour: memory
faults/segmentation violations
char* int2string(int i) { char buffer[64]; sprintf(buffer, "%d", i); return buffer; }Local arrays (in C these are called automatic variables) are allocated on the stack and are removed as soon as the function returns. The pointer (in this case
buffer
) will then be invalid. This will work:
char* int2string(int i) { char* buffer; buffer = new char[64]; sprintf(buffer, "%d", i); return buffer; }
scanf("%d", value)
instead of scanf("%d", &value)
. The first
will most of the time result in a memory fault.
When compiling with -Wall
, gcc will give a warning: test.cc:8: warning: format argument is not a pointer (arg 2)
.