In programming, a gotcha is a feature of a system, a program or a programming language that works in the way it is documented but is counter-intuitive and almost invites mistakes because it is both enticingly easy to invoke and completely unexpected and/or unreasonable in its outcome.
Equality operator
The classic gotcha in C is the fact that
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
which executes code if a and b are equal. Modern compilers will generate a warning when encountering this construct. To avoid this gotcha, some programmers 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. Others find this workaround yields hard-to-read code.
Function calls
Example from C and relatives:
will produce (when compiled and run):
What foo; expression counterintuitively does is returning the address of the function foo. What the programmer intended was probably instead the function call:
where the parenthesis indicates a function call with zero arguments.
Initializer lists
In C++, it is the order of the class inheritance and of the member variables that determine the initialization order, not the order of an initializer list:
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
programming language
Javascript function closures inside loops don’t work intuitively.
correct way:
Scoping
Scope of a local variable starts at its definition and ends at the end of the method. Within its scope, the local variable obscures current object's methods.