From Surf Wiki (app.surf) — the open knowledge base
Gotcha (programming)
Code that is valid but counter-intuitive
Code that is valid but counter-intuitive
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.
Example
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. 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 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.
References
References
- [http://catb.org/jargon/html/G/gotcha.html Gotcha definition at The Jargon File]
- [https://www.securecoding.cert.org/confluence/display/c/VOID+EXP21-C.+Place+constants+on+the+left+of+equality+comparisons "VOID EXP21-C. Place constants on the left of equality comparisons"]
This article was imported from Wikipedia and is available under the Creative Commons Attribution-ShareAlike 4.0 License. Content has been adapted to SurfDoc format. Original contributors can be found on the article history page.
Ask Mako anything about Gotcha (programming) — get instant answers, deeper analysis, and related topics.
Research with MakoFree with your Surf account
Create a free account to save articles, ask Mako questions, and organize your research.
Sign up freeThis content may have been generated or modified by AI. CloudSurf Software LLC is not responsible for the accuracy, completeness, or reliability of AI-generated content. Always verify important information from primary sources.
Report