Template:Short description 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.<ref name=jf/>

ExampleEdit

The classic gotcha in C/C++ is the construct <syntaxhighlight lang="c"> if (a = b) code; </syntaxhighlight> 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 <syntaxhighlight lang="c"> if (a == b) code; </syntaxhighlight> which executes code if a and b are equal.<ref name=jf>Gotcha definition at The Jargon File</ref> Modern compilers will usually generate a warning when encountering the former construct (conditional branch on assignment, not comparison), depending on compiler options (e.g., the -Wall option for gcc). To avoid this gotcha, some programming languages such include specific syntax for when this is desired behavior, such as Python's "walrus" operator (:=). In languages where this specific syntax does not exist, there is a recommendation<ref>"VOID EXP21-C. Place constants on the left of equality comparisons"</ref> 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 Yoda conditions). Many kinds of gotchas are not detected by compilers, however.Template:Cn

See alsoEdit

ReferencesEdit

Template:Reflist

Further readingEdit

External linksEdit

Template:Sister project

  • C Traps and Pitfalls by Andrew Koenig
  • 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