Gotcha
From Wikipedia, the free encyclopedia
- For other uses of "Gotcha", see Gotcha (disambiguation).
A gotcha refers to a detrimental condition (usually of a contract or agreement) that is designed to sneak past the other party. For example, many "free" Credit Report sites have "gotchas" that automatically sign you up for a monthly credit report service unless you explicitly cancel. A gotcha is also a frequently used programming term.
Contents |
[edit] Programming Gotchas
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.
[edit] Gotchas in the C Programing Language
[edit] Equal Gotcha
The classic gotcha in C is the fact that
if (a=b) code;
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
if (a==b) code;
which executes "code" if "a" and "b" are equal.
[edit] Function Gotcha
In C and C++, function calls that need no arguments still require parentheses. If these are omitted the program will still compile, but will not produce the expected results. For example:
#include <iostream> using namespace std; int myfunc(){ return 42; } int main (){ cout<< myfunc; return 0; }
The program will only display the expected result (the string '42') if the form cout<< myfunc(); is used. If the shown form cout<< myfunc; is used, the address of the function myfunc is cast to a boolean value, and the program will instead display the string '1'.
[edit] Gotchas in the C++ programing language
[edit] Initializer List Gotcha
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:
#include <iostream> class CSomeClass { public: CSomeClass(int n) { std::cout << "CSomeClass constructor with value "; std::cout << n << std::endl; } }; class CSomeOtherClass { public: CSomeOtherClass() //In this example, despite the list order, : obj2(2), obj1(1) //obj1 will be initialized before obj2. { //Do nothing. } private: CSomeClass obj1; CSomeClass obj2; }; int main(void) { CSomeOtherClass obj; return 0; }