You know the ones that make you go WTH and are easily spotted by a coworker just passing by?
Please keep it one gotcha per answer to simplify voting.
You know the ones that make you go WTH and are easily spotted by a coworker just passing by?
Please keep it one gotcha per answer to simplify voting.
I was stumped by:
int i = 0;
while (i < 100);
{
//do stuff
i++;
}
But the compiler warning proved very helpful!
if (status = UNDER_ATTACK) {
launch_nuclear_missiles();
}
For me, when returning to C or C++ after lots of time in the Java/C# world, I always always forget that class and struct declarations end with a semicolon.
So I do a C# style
class foo {
}
And scratch my head at the compiler errors.
public class FooHolder
{
private String foo;
public void setFoo(String foo)
{
foo = foo;
}
}
I've heard stories about people setting values to null:
if (foo = null) { .. }
so a good way to prevent that is to put the constant first
if (null = foo) { .. } //should nearly always throw an error or warning
I personally never really encounter these syntactical errors.
Overloading an operator and forget that you have overloaded it. Few time later, you have weird behavior and you do not understand why the code is acting weird... then you realize the operator change the behavior.
Exemple : == with NULL was always returning true...
Prior to Eclipse:
class Person {
Person (String name) {
//parameter assigned to itself as field hidden
name = name;
}
private String name;
}
I share this with new developers who hate strict datatypes in .NET languages:
VB6 was very liberal in type checking, and if omitted it would assume variant. This caused many odd results as it tried to assume the datatype. For example:
Dim x, y As Integer
Would result in y being defined as an Integer and x being defined as a Variant.
Oddities like this resulted in a lot of debugging, but gave me some easy tests to screen prospective developers.
Forgetting to declare an interface or a class as public has sent me for a loop more than once.
Oh! And when using Rhino Mocks to mock a class, forgetting to make a method virtual
In C++
Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype
Querying for results and then trying to eliminate unwanted records...
DELETE Users
SELECT *
FROM Users u
WHERE u.Reputation > 10000
I don't like the fact that braces are optional in C-like languages if you only have a single line after a conditional. For example:
if( x )
foo();
Many years ago, I hastily edited a statement like that to read:
if( x )
bar();
foo();
It took me a lot longer than it should have to fix that bug. So, now my rule is that if I don't have braces, everything goes on the same line. So, this is OK:
if( x ) foo();
(C#) Scoping within switch, which makes this illegal:
switch (something)
{
case 0:
int x = 10;
...
break;
case 1:
int x = 20; // No, still in same scope as case 0...
...
break;
}
If you add appropriate braces, it works of course.
(Java) Being able to refer to static members through expressions:
Thread t = new Thread(...);
t.start();
t.sleep(1000); // Which thread does it look like this will affect?
Fortunately Eclipse warns about this.
The trailing semi-colon on a conditional in C/C++
if (status == -1);
{
printf("failed\n");
}
I've spent hours not finding that...
In c# creating a new class in a new file and not explicitly declaring it public.
Forgetting a MoveNext in a classic ASP recordset loop
while rs.EOF = false
Response.Write rs("name")
wend
If I want to declare a list/array inline in Java, C# and C++ I think, I've gotta use braces.
Braces are otherwise used for one thing: to denote logical blocks.
I don't consider the elements of a list a logical block of code. I have to look up inline list declaration every time.
Why can't I do new array(foo, bar, qaz, bin, barz)
to declare an array?
Rethrowing exception in C#. This causes grief for every Java developer I've met who later used C# {sarcasm} even though everyone knows that C# and Java are basically the same! {/sarcasm}:
try {
...
} catch(Exception e) {
//Do something
throw; //Correct C# syntax, compiler error in Java
//throw e; //Correct Java syntax, compiles in C# but undesired behavior (rewrites stack)
}
In C++ or C, this one always used to get me back in the day (depending I'm sure on your compiler and/or IDE):
my main.C:
#include "SomeClass.H"
int foo() { // Compiler gives cryptic error message here about the declared type of foo().
...
}
my SomeClass.H:
class SomeClass {
...
} // <- No semicolon
It took me many times of making that mistake before I finally caught on that the compiler was really just trying to tell me "missing semicolon at the end of your include file". Why the compiler(s) could never figure that out and give me a proper error message, I'll never know.
(C#) The \x escape. Quick, how different are "\x9Good compiler" and "\x9Bad compiler"?
While I hate that you can do an if statement without having to use brackets, the biggest "gotcha" problem I've seen is when you mistakenly do something like:
if (x = y)
{
// do stuff
}
It will produce strange results until you realize that you're actually assigning the value of y to x.
Spent a while on this one recently (C/C++)
// Change / to \
UnixToDosPath(path);
The \ is followed by a space, which means that the VS2005 syntax coloration treats the next line as real code, and compiles it as such, while GCC (arm-elf-gcc 4.2.2) treats it as a comment, but despite what the documentation says, does not warn about the trailing space. Both are correct, since this behaviour is implementation defined in C99. Eventually asked for a second pair of eyes from another engineer, who spotted the problem instantly...
This one made my coworkers laugh, including my boss...
void someclass::foo( int a )
{
switch( int a )
{
// ... wtf?
}
}
It took me like 5 minutes until I realized what was going on.
Ruby:
bill=5 => 5 bi11=bill+5 => 10 bill => 5
I've been bit with that back in the wild days of programming languages, and it is such a horrible bug that it's amazing that any new language won't give you a way around it.
Even Visual Basic has Option Explicit, and I've been in interviews where the first question was "What's the first line of every VB file" and if you didn't respond "Option Explicit" they said "Have a nice day".
The most annoying syntax gotcha in Perl:
my $value=something() if ($condition);
This post of mine got 14 up votes, and I consider it a pretty big gotcha. Basically it boils down to that in in VB.Net, the syntax for getting item "i" in an array, and for calling function and passing in "i" are exactly identical. Also, you can call a function without using the parentheses. So, the following code can represent 3 things
Foo(Bar)
In Java:
if (someString == "Y"){
... never executes this code, even when someString.equals("Y") ...
}
Old school VB. Doesn't fast-terminate the logic statement when something is false.
Function testString(s As String)
MsgBox "Should not be called"
End Function
Dim s As String
If Len(s) > 2 And test(s) Then
MsgBox "Starts With A"
End If
Forgetting the second "fetch next" statement in a SQL Server cursor.
fetch next from cursor1 into @var1, @var2
while @@fetch_status = 0
begin
--Do something here
--always seem to forget this next line
fetch next from cursor1 into @var1, @var2
end
Java:
String s = "a1";
s.replaceAll("a","b");
//expect s to become "b1"
Python: I've got some list of strings:
important_strings = [ 'one',
'two',
'three',
'four'
]
Later, I realise that 'five' is important too:
important_strings = [ 'one',
'two',
'three',
'four'
'five'
]
...
(solution: end every line with a comma. this is fine in python: lst = [1, 2, 3, ] )
The easily forgotten global keyword in Python.
counter = 0
def increment():
counter += 1
I frequently switch between Java and Flash.
I will often start writing my Java functions
private function foo():int {
}
and my Flash functions
private int foo() {
}
In C++, if you forget a semicolon after class declaration in header file, then the many .cpp files in which the .h is included will start reporting compile errors. You may go crazy trying to figure out the cause of those esoteric and strange errors - unless you know where to look - for a recently modified .h file.
C++
Classic one this is, you go to declare a template or something that uses templates like so:
list<vector<string>> squirrels; // FAIL!
the >> is interpreted as the shift operator, white space required!
Edit: this would give you a syntax error though but annoying!
We've all done the other way round; am I the only person who has written
x == 1;
and spent ages wondering why x wasn't changing?
goran.siska pointed this one out:
int i = 0;
while (i < 100);
{
//do stuff
i++;
}
I ran into this many years back, but to make matters worse, the compiler I was using did not catch it, and a bunch of indentations and conditions made it so the semicolon was on character position 81, in an 80 character wide IDE...
As much as I love LINQ I can't for the life of me work out why JOIN's are like this:
var results = from item in source
join otherItem in otherSource on item.Id equals otherItem.ItemId
where item.Property == someVal
select item;
equals! Why is the equallity comparison done with the keyword equals when every other C# equality comparioson is with ==
Test if result of a functioncall is 0, storing into a variable:
if (avar=func() == 0) { }
Evaluates to:
if (avar = (func() == 0)) {}
Which is not what you want...
C++. Notice nasty semicolon after if... Took me some time to find this bug. Solaris compiler gave no warning or anything. I guess I was auto-competition error from SlickEdit. My team does not use it anymore...
if(foo == bar);
{
doSth();
}
Extra comma in a JavaScript object literal:
var options = {
title: "Foo",
readOnly: true,
width: 300,
//color: "#333"
};
The last line may just be commented out or deleted. Firefox/Safari/Opera/Chrome won't complain about the extra comma after the width
property. IE6 will stall in its tracks and won't even process any of your code. You'll have lots of fun looking for that single extra comma (JSLint helps).
Loading a Java properties file on a Windows system:
pathToOutput=C:\Documents And Settings\Clifton\MyJavaOutput\
Then cussing because your app is producing no output after several invocations even after mashing the F5 key 72 times, then crying because you've littered your C drive with the explosion of repeat debug cycles.
Here's one of my favorites:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="MyTemplate">
<xsl:template>
</xsl:stylesheet>
In Java it's the source of the java.util.EmptyStackException And for what it's worth I have a deep suspicion this same easily overlooked problem is at the root of many other complaints and bug reports regarding the exception. Jasper pre-compilation, XSL-fo issues and more can probably be traced to it. I wonder how many man hours have been exhausted trying to understand it.
I often switch between Java, JavaScript, PHP, Lua, VBScript...
When concatenating strings, I am sometime confused whether I should use . .. + or &
I find the choice of + the worst one, particularly in Java where it is the only exception to absence of operator overloading...
function bool funcName()
{
bool blnReturnValue;
//processing to determine the value of blnReturnValue
if (blnReturnValue == true)
return true;
else
return false;
}
Instead of just returning blnReturnValue. I think this was actually mentioned on the Stack Overflow podcast a while back.
Octal numbers in C (and some other languages).
if(42 != 042)
printf("WTF?!");
The constructor+field initialization syntax in C# 3.0 is very convenient, but I keep making the same mistake.
Correct:
var d = new DeepThought()
{
Answer = "42", //note a comma
YearsToWait = 15000000 //you may put a comma here as well (but aren't required to)
}; //this is actually an end of statement, so the semicolon is mandatory
My wrong version:
var d = new DeepThought()
{ //hey, this looks like a code block!
Answer = "42"; //all my life I've been using semicolons as separators.
YearsToWait = 15000000; //I'm not going to change my habits, you stupid compiler!
} //why do I need to put a semicolon after a curly?
Yes, I understand why the correct version is correct and mine is erroneous, but my reflexes trick me every time.
I type fast, so this one is my latest peeve:
public class Foo {
public Foo(int bar)
{
this.Bar = Bar;
}
public int Bar { get; private set; }
}
Yeah, that's caught me a number of times lately. Usually, it's because I'm not paying attention when Intellisense pops up. Grrr...
Python:
(A semantics gotcha, not a syntax one, but in the same spirit)
The famous "mutable default arguments are initialized once" gotcha.
def f1(arg=list()):
arg.append(1)
return arg
for ii in "surprising":
print f1()
[1]
[1, 1]
[1, 1, 1]
[1, 1, 1, 1]
[1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
A better way to handle this is:
def f2(arg=None):
if arg is None: arg=list()
arg.append(1)
return arg
for ii in "better":
print f2()
[1]
[1]
[1]
[1]
[1]
[1]
In Visual Basic and Visual Basic for Applications, IIf is not a statement, but a function. Which means that something like this:
values = IIf(divisor = 0, 0, numerator / divisor)
Still raises a divide by zero error because both the true part and the false part are calculated before the condition is checked and a result is returned.
I once had this line in my Sudoku solver for my AI class:
if(some_condition);
do_something();
Of course, do_something() was happening on every run-through, even on ones where I was 100% positive it shouldn't. I spent over 2 hours in the debugger, looking at variables and stepping over the 2 lines, until I noticed. I wanted to punch a hole in the wall.
In OCaml:
let mylist = [1, 2, 3];
(* How many elements does this list have? *)
(Ruby)
class Foo
attr_accessor :bar
attr_accessor :qux
def initialize
self.bar = "bar"
self.qux = "qux"
end
def baz
qux = bar # you can drop the 'self.' for accessing, but not assigning
# this is actually assigning a local variable qux.
end
end
>> foo = Foo.new
>> foo.bar
=> "bar"
>> foo.qux
=> "qux"
>> foo.baz
=> "bar"
>> foo.qux
=> "qux"
here is one I've spent a while figuring out several years back (Python):
def f(a, b=[]):
b += [a] * a
print a
pretty straight forward, right?
now here we use it:
f(1) # obviously prints [1]
f(1) # prints [1, 1] can you guess why? :)
int main()
{
unsigned long long c = 0;
unsigned long a = 895753940;
unsigned long b = 2832960749;
c = (a*100)/b;
}
Seems like it should work. The result should easily fit in the long long. But the result is incorrect. It appears that the type of this expression is either the type of a or b depending on which is bigger and not the type of c.
// double-loop:
for(int i=0; i<10; ++i){
for(int j=0; i<10; ++j){
// do something
}
}
My favorite infinite loop. It can happen in a lot of languages. Example in C:
unsigned u;
for (u = 10; u >= 0; --u)
printf("%u\n", u);
Errors that that complains about class Foo
when I didn't include Foo.h...
The following Python gotcha. Default arguments.
def func(arg=[]):
arg.append(1)
print arg
>> func()
"[1]"
>> func()
"[1, 1]"
The default argument is mutable, so it will use the same reference each time. A better solution would be this, which does what you would expect.
def func(arg=None):
if not arg:
arg = []
arg.append(1)
print arg
At great risk of provoking a religious war over programming languages...
Aside from backward compatibility, new programming languages should NOT be case sensitive!
Compiler Warning: undefined identifier 'NOT'
Oh who can forget the case sensitivity problem when calling methods (not necessarily always a bad thing) when it lets you do:
public void Foo() {/*...*/}
//...
foo();
An inherited codebase wasn't made with much concern for data types, leading to mystery troubles caused by this attempted boolean evaluation where anything non-zero should be considered true...
php > $onezero = '0';
php > $twozeros = '00';
php > var_dump($onezero,$twozeros);
string(1) "0"
string(2) "00"
php > echo (! $onezero ) ? 'false' : 'true' ;
false
php > echo (! $twozeros ) ? 'false' : 'true' ;
true
I really like this one:
public class ArgTest {
public static void main(String[] args) {
int count = 0;
int sum = 0;
for (int i = 0; i < args.length; ++i) {
try { /* If we get a
int thisint = * NumberFormatException,
Integer.parseInt(args[i]); * here, "count" won't
count++; * be incremented.
sum += thisint; */
}
catch (NumberFormatException e) {
}
} // for
System.out.println(count + " valid integers.");
System.out.println("The sum is " + sum + ".");
} // main
} // class ArgTest
I've never seen anyone do it for real, though.
C#
class Whatever : ISuchAndSuch { // sorry, no can use this here ISuchAndSuch _such = this; // sorry, no can define delegates here public event Action<int> _callback = new Action<int>(DefaultCallback); void DefaultCallback(int obj) { } }
bool SomeCheck(){
return false;
}
void myFunc(){
if(SomeCheck){
// will always run
}
}
Back as a newbie programmer this one got me (no warning from the compiler). Thankfully all the compilers I use these days generate a warning.
class Bobo{
public:
Bobo(int i):b(i),a(b)
{
assert(a==b); //almost guaranteed to fail
}
private:
int a;
int b;
};
Can anyone explain why I can't even get a warning on this one?
switch case fallthrough. Deadly; hard to spot, hard to learn to avoid. And would have been so easy to leave out of the language(s) in the first place...
if request.method == "POST"
[do stuff]
else
[other stuff]
For me it's the darn colon after if and for statements in Python. I forget it almost 90% of the time.
Back when I was doing PHP a lot, whenever I'd load up a page that would render that all-to-familiar white screen with the black error text at the top, without even thinking I'd say to myself "Whoops, forgot a semicolon". Now that I'm suing Python, the deluge of forgotten semicolon syntax errors are replaced by forgotten colon syntax errors.
After five years programming in C#, I was involved in a Java project. I caught in an irritating trap about a thousand times: trying to compare strings with ==
. And the IDE didn't even throw a warning. Ugh.
typedef unsigned char UINT8;
void Foo( void )
{
UINT8 i;
for( i = 0; i < 256; i++ )
{
// Do something
}
}
Oops! - It's an infinite loop
int i=0;
NSLog(@"%@",i); //getting too used to printing out objects, compiles but manifests a EXC_BAD_ACCESS
In VB.Net:
Dim x = SomeObject.Member1 ' Is this a method or a property? We can omit the ()
Dim y = SomeObject.Member2()() ' When the property returns a delegate, then we can't omit the ()
Dim z = SomeObject.Member3()(0) ' Maybe 0 is a parameter for a delegate returned by Member3?
Dim d = SomeObject.Member4()(0) ' Or are we accessing the first member of an collection?
VB.Net is sometimes confusing. You can sometimes omit the braces or a method call or a property. When accessing an collection like an array or IEnumerable, you use () instead of [].
#!/bin/bash
if [$1 == "world"]; then
echo "Hello, $1"
fi
on Cygwin it's giving me a different error than it originally did under Ubuntu. The error it was giving me was on the wrong line completely.