Jump to content

Gotcha (programming)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Michael9422 (talk | contribs) at 20:16, 8 July 2016 (→‎External Links: format change; add description from cover). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In programming, a gotcha is a valid construct in 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 /C++ is the construct

if (a = b) code;

It is syntactically valid: it puts the value of b into a and then executes code if a is non-zero. Sometimes this is even intended. However most commonly it is a typo: the programmer probably meant

if (a == b) code;

which executes code if a and b are equal.[1] Modern compilers will usually generate a warning when encountering this construct. To avoid this gotcha, there is a recommendation[2] to keep 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.

See also

References

Further reading

  • Stephen C. Dewhurst (2003). C++ Gotchas (Avoiding Common Problems in Coding and Design). Addison-Wesley. ISBN 0321125185.

External Links

  • C++ Gotchas A programmer's guide to avoiding and correcting ninety-nine of the most common, destructive, and interesting C++ design and programming errors, by Stephen C. Dewhurst