- Gotcha (programming)
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.
Gotchas in the C programing language
Equality operator
The classic gotcha in C is the fact thatis syntactically valid and sometimes even correct. It puts the value of
b
intoa
and then executescode
ifa
is non-zero. What the programmer probably meant waswhich executescode
ifa
andb
are equal. To avoid this gotcha, it is recommended to keep the constants in the left side of the comparison, i.e.42 = meaning_of_life
rather thanmeaning_of_life = 42
.Function calls
Example from computer languages such as C:
Gotchas in the C++ programming language
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:
Gotchas in Ruby programing language
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.
Iterating Range
Ruby has a data type called Range; an object of this type constitutes a set of everything between the start and end of the range (including or not including the boundaries, depending on additional conditions). Since Range is a subclass of Enumerable, one would intuitively expect that iterating a valid Range object will give you every single object in that set, from start to end. This expectation turns out to be incorrect:
Returns from the block
return
statement returns from the context it was defined in, not from the context it's currently executed in. For example:One might expect that
return
would allow the transaction to be properly closed, but unfortunately that's not the case -- the code in transaction() taking care of that will never be executed if something=true.Implicit exception catching
One would expect that the
rescue
block would catch any exception thrown, but this is not true -- it will only catchRuntimeError
(which is a subclass ofStandardError
, which in turn is a subclass ofException
). If you intend to catch all exceptions indeed, the following syntax should be used:External links
* [http://www.hyperdictionary.com/computing/gotcha from the HyperDictionary]
Wikimedia Foundation. 2010.