Gotcha (programming)
In programming, a gotcha is a feature of a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome.[1]
The classic gotcha in C is the fact that
if (a=b) code;
is syntactically valid and sometimes even correct. It puts the value of b
into a
and then executes code
if a
is non-zero. What the programmer probably meant was
if (a==b) code;
which executes code
if a
and b
are equal.[1] Modern compilers will generate a warning when encountering this construct. To avoid this gotcha, some programmers[2] recommend keeping the constants in the left side of the comparison, e.g. 42 == x
rather than x == 42
. This way, using =
instead of ==
will cause a compiler error.