views:

9410

answers:

90

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.

+92  A: 

I was stumped by:

    int i = 0;
    while (i < 100);
    {
        //do stuff
        i++;
    }

But the compiler warning proved very helpful!

Goran
This has caused almost as many headaches as *missing* semicolons.
Bill the Lizard
That must be one of mine. I starred at your snippet for about a minute going, "Huh? What's the problem" :P
Dana
Yes i hate this. Language designers of the future should specifically disallow this construction.
PeterAllenWebb
Adding a ; at the end of the line gets to be automatic :)
Goran
@PeterAllenWebb you'd miss some of the cool statements like while (*p++ = *q++); to copy a string
Kyle Cronin
I had to load this up into a project as i'd never seen it personally. I understand now :)
Cetra
I changed my mind. I JUST experienced the same error in PHP - it's very frustrating (especially since the compiler doesn't make a peep about it).
Kyle Cronin
another great reason to use the one true brace style! huzzah!
nickf
@goran.siska.myopenid.com: ECMAScript (aka JavaScript) automaticly adds Semicolons (in certain situations) see §7.9 :-)
jk
@nobody: you would´t. you could do while (*p++ = *q++) {};
Leonel Martins
I may be an old fart, but IMO, syntax like (*p++ = *q++); to copy a string is only 'cool' in a theoretical, syntactic elegance kind of way. It's an example of intellectualising at the expense of readability. In truth, any fool can learn this sort of thing. But only fools think it's clever.
ChrisA
@Goran: That's why I prefer to use `int i = 100; while (i--) { /* do stuff */ }` when I can!
Ben Blank
There is nothing wrong with this. The while loop doesn't execute, and the i++ is scoped.
Yktula
+160  A: 
if (status = UNDER_ATTACK) {
    launch_nuclear_missiles();
}
Bill the Lizard
A simple one but one that definitely got me when I was starting out.
Ross
Yeah, I've put code into production with this sort of bug before.
SpoonMeiser
This one is really annoying, especially after a bunch of assignments before the if statement
Fry
Whenever I'm tired and up against a deadline, this one's always there to guide me along.
Joeri Sebrechts
this is a hard one if you have been doing some VB before hand
Tanj
@Tanj: Or SQL. Switching between T-SQL stored procedures and .NET code too often regularly causes this kind of problem in one of the two places.
Yadyn
Oh lordy this one is insidious.
Magsol
The really scary part is I've occasionally found this bug/feature useful. It's a really scary syntax but ...if ( Foo* p = TryGetSomeValue() ) { ...}Scary but oh so tantalizing
JaredPar
@SpoonMeister: I found one of those in production code that must have been at least 2 years old the other day. I wasn't even looking for a bug, just spotted it and the syntax alarms started going off in my head :)
Dan
It took me a while to understand why the previous developer was in the habit of writing: if (UNDER_ATTACK == status).....
Adam Liss
So remind me why everyone seems to prefer C# to VB? For this to persist as a real-world problem in a top-tier language is just bizarre.
ChrisA
@ChrisA - this would generate a syntax error in C#. Actually, it will generate a warning in any modern C or C++ compiler as well if people would only set the warning level high enough.
Ferruccio
Is it any wonder that a C problem makes the top of the list?
Loren Pechtel
Oddly enough, I use while( $obj = $collection->next() ) in PHP quite lot. Maybe using it in while() is more intuitive than in if().
staticsan
@Loren Pechtel: I'm sure its position is helped by the brilliant sample usage :)
Jerph
In our code we have tens of thousands of places of the sort: if (value = get_value_one_way()) { value = get_value_another_way();} Thus, we turned the warning for this off... Who knows, we might also we have some legitimate errors.
Daniel Rose
At least going from coding VB to Python will generate plenty of errors that don't allow you to execute.
Wayne Werner
A: 
if(calculateSomething()){
   return true;
}
else {
   return false;  
}
EricBouwers
you should get a syntax error for this one ... the else do not correspond to any if !
PierreBdR
what? I don't see any problem here, am I blind?
D4V360
It's not a syntax gotcha, but it can be simplified to: return calculateSomething().
asterite
I don't see it either. It can probably be re-written nicer as "return calculateSomething()" is calculateSomething returns a bool, but other than that...
SpoonMeiser
return calculateSomething();
Bill the Lizard
-1 because it's not a "gotcha", just bad style.
Outlaw Programmer
+44  A: 

Should be obvious from my name. Forgotten Semicolon.

Forgotten Semicolon
That used to be my (least) favorite thing to explain to my boss.
Bill the Lizard
Upvoting for the name reference.
leek
Oh man, I love getting 100 compiler errors, none of which actually point to where the mistake is.
andy
Upvoted. But maybe you should edit this answer to be more specific. Once community wiki kicks in and your name disappears, this answer won't make any sense. ;)
MrValdez
@MrValdez: Done!
Forgotten Semicolon
upvoted. I would have been in a jail by now.
Mohamed
andy: do you know what we do, then? We switch to a better compiler. I think LLVM/Clang can diagnose this well, but I'm not sure.
Yktula
+35  A: 
if( x & 3 == 1)
{
    // This will never be run.
}
Robert
I've spent hours debugging things like this...
rmeador
SpoonMeiser
Robert
nickf
Bdoserror
Better written as if(x % 2 == 1), I think.
Cristián Romo
Eclipse
strager
@strager - that would be EVIL!!
Robert
Oualline's rule from "Practical C": There are fifteen precedence rules in C (...). The practical programmer reduces these to two: 1) Multiplication and division come before addition and subtraction. 2) Put parentheses around everything else.
Michael Burr
I have my own two rules: 1) Use parentheses whenever you're uncertain. 2) Never study the precedence table. Works for me: not too many parentheses, and nobody complains about my expressions.
David Thornley
Chris Lutz
+12  A: 

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.

Dana
This one gets me in perl - eval {} needs a semicolon. Since I usually use it as a nicely indented try-catch block ( eval{} if($@){} ), and putting the if _after_ the statement is legal syntax, the resulting syntax error usually confuses the hell out of perl (and me).
Ant P.
Finally VC++ takes pity on us and tells you this - instead of just generating a few 100 error messages for the class.cpp
Martin Beckett
+22  A: 
public class FooHolder
{
  private String foo;

  public void setFoo(String foo)
  {
    foo = foo;
  }
}
davetron5000
I don't feel like recompiling my giant C++ app to test if that will work in C++, but I think it will. It definitely works in Java. The method parameter hides the variable in the higher scope. It's common in java to see this.foo = foo for setters.
rmeador
Any IDE worth it's salt should flag this one instantly. You could also declare all parameters as final to protect against this.
Outlaw Programmer
Any X worth it's Y would notice Z instantly.
davetron5000
Using a good naming convention for properties and their backing fields will keep this from happening.
Robert Rossney
Yes it works in C++ as well, as pretty much the same scoping rules apply. Fairly common workaround is to have a standard prefix on class members and/or method parameters.
workmad3
That standard prefix might even be something like "this."
Greg D
With syntax coloring it's easy to see when this happens, as I have parameters/local variables and fields colored differently.
ColinD
In Java I habitually make anything that isn't declared in a for loop initialiser final, including arguments.
Pete Kirkham
My coworkers will do this with varying degrees of success and it drives me mad. I got bitten by this several times a few years ago and ever since I will never use the same word as vars of diff scopes. Apparently, I'm too careless and/or forgetful to do it right so I don't do it at all.
Dinah
+17  A: 

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.

Joe Philllips
the foo = null will throw a warning with any decent compiler. the null = foo will throw an error. Regardless, I consider the first form more readable. It's a mistake I almost never make, and the compiler warning saves me if I do. Never release code that has warnings.
rmeador
though i find that putting the variable on the left to be much more readable ("if x is equal to 5" > "if 5 is equal to x"), that's actually a really good way to avoid that all-too-common error. good tip!
nickf
Definitely useful for JavaScript programming
Mike Robinson
Good tip if one of your operands is a constant, but doesn't work for if(x = y){...}
Bill the Lizard
+2  A: 

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...

Daok
A: 

Prior to Eclipse:

class Person {
    Person (String name) {
        //parameter assigned to itself as field hidden
        name = name;
    }
    private String name;
}
Garth Gilmour
+2  A: 

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.

polara
A: 

Forgetting to declare an interface or a class as public has sent me for a loop more than once.

George Mauer
Not sure if this is really a "gotcha". Most of the other examples will still cause your code to compile, but it will have bugs. This one will probably cause a compile time error (in Java anyway).
Outlaw Programmer
A: 

Oh! And when using Rhino Mocks to mock a class, forgetting to make a method virtual

George Mauer
+29  A: 

In C++

Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype
Garth Gilmour
This is an annoying C feature that C++ inherited. As if anyone in the world has ever declared a function IN THE MIDDLE OF ANOTHER FUNCTION.
rlbond
+3  A: 

Querying for results and then trying to eliminate unwanted records...

DELETE Users
SELECT *
FROM Users u
WHERE u.Reputation > 10000
Goran
That's not really a syntax problem so much as having a basic misunderstanding of the language.
Joe Philllips
Actually I use the select to make sure I'm getting correct results and then just replacing the select line (adding -- to comment it out) with delete line. The problem occurs when I forget to comment the select line and this becomes two queries. What is my basic misunderstanding?
Goran
I have a habit of putting the DELETE/UPDATE after the select and starting it with -- If I accidentally run the entire batch the select runs and the delete is ignored. I have to highlight the DELETE statement from after the comment character to execute the delete. It's saved me a few times.
Darrel Miller
By the way, nice example.
kbrinley
DELETE FROM students; WHERE students.reg_date < '2008-09-01';
+61  A: 

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();
twk
Not a bad compromise to the "always require braces" debate.
Bill the Lizard
Yeah, I was in that camp for a while. But, then I started buying into the whole religion about reducing lines of code.
twk
The problem is that Visual Studio 2008 C# editor will automatically reformat the single line to two separate lines. I hate this behavior, but can't yet change it. I have to waste two lines and add parenthesis. (Note: auto-reformatting happens under several conditions, one being cut and paste.)
Mark T
This is EXACTLY why I (and others) advocate always being explicit with your conditional code blocks, even if its only one line. http://www.joelonsoftware.com/articles/Wrong.html
Yadyn
That's why you should run *indent* on your code as often as possible.
Cristian Ciupitu
I like to avoid fighting the IDE because it's a waste of time to do so...
alord1689
to me, doing this:if(x){ foo();}instead of this:if(x) foo();is the same thing as doing this:x = (y+z);instead ofx = y+z;it's unecessary and ugly.
Kevin
My standard is always use braces unless it is very, very, very, very obvious.
Paul Nathan
+1 for running an indent tool as part of each build.
Pete Kirkham
I just use python :)
defrex
@Paul Nathan - thats worse, it means only get the bug where you never, never, never look ;-)Always use {} even when it's empty!
Martin Beckett
Bah. A better rule is to not make this mistake. Braces for single-liners is ugly.
rlbond
+31  A: 

(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.

Jon Skeet
Doing work inside case branches is ugly anyways. If I have to use switch/case, the cases only contain calls to methods which do the work.
EricSchaefer
Same with C++. Catches me many times. =[
strager
Huh - never knew you could add braces to case branches.
Erik Forbes
Weird - also never knew you could arbitrarily use braces to create little pockets of scope... *boggle*
Erik Forbes
@ErikAre braces ever really used for anything besides scoping?
Matt Davison
@Erik: You can put braces around every code block you like.
VVS
@Erik: you can add braces to *anything*. This is legal: if(foo) {{{{bar();}}}}
Zifre
@VVS: wow, it's kind of weird that we both posted the same comment within 5 seconds of each other on a 6 month old post.
Zifre
I dislike VB, but Select statements are much more beautiful than switch`es in c#.
Arnis L.
In C++ you have to use braces in the case: if you want to define a variable. Never been entirely clear why - other than it being a 'feature' of the original C parser.
Martin Beckett
+61  A: 
int* y,z;

This is just a failing of the language :(

JaredPar
another good reason why declarations should be on their own line
Joe Philllips
Wow, no kidding. This always annoys me.
twk
This is a good reason to switch to the convention of: int *y,z;
Wedge
jk
I deliberately avoid putting the '*' next to the type for this very reason. Although I agree that it would make more sense if the '*' bound to the type instead of the variable name, the fact is that it doesn't. You're just writing something different to what the language syntax really means.
Simon Howard
typedef /*@only@*/ int * int_ptr; \n int_ptr y,z;
Pete Kirkham
So, excuse my C/C++ ignorance here, but is y a pointer to int and z an int? That's all I could come up with.
Ed Swangren
Got it in one, Ed.
David Thornley
I think it's great. If you need two pointers, you can just use `int *y, *z;`.
Yktula
+52  A: 

(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.

Jon Skeet
Is this an Eclipse feature or compiler feature?
Robert
A feature of the Eclipse JDT compiler.
Jon Skeet
I've seen warnings for accessing static methods through instances before but never really thought it could cause harm. I'll keep my eye out for this one!
Outlaw Programmer
VB lets you call static methods on Nothing (null), as long as you cast it to the right type
Jacob
Ha, C++ lets you call instance methods on null, as long as you cast it to the right type!
Until I read this, I considered being able to call static methods through an instance reference a feature. Now I know better...
Michael Burr
Yes, a very good point indeed Mr Skeet. I remember this from my Java days.
DoctaJonez
+3  A: 

The trailing semi-colon on a conditional in C/C++

 if (status == -1);
 {
     printf("failed\n");
 }

I've spent hours not finding that...

JayG
A: 

In c# creating a new class in a new file and not explicitly declaring it public.

Fry
+27  A: 

Forgetting a MoveNext in a classic ASP recordset loop

while rs.EOF = false
    Response.Write rs("name")
wend
harriyott
Forgetting MoveNext was especially fun if you were copying rows from one database to another. Somehow the destination computer would get filled up and crash.
MusiGenesis
I hated this one...
alord1689
and worse was smashing F5, moaning atthe network while all the time your hammering the poor webserver :(
Amadiere
I did something like that so many times I actually put a sticky note on my monitor that said "rs.MoveNext".
Corin
+2  A: 

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?

Ryan
Oh, you'd /love/ Perl...
SpoonMeiser
+13  A: 

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)
}
James Schek
I'm not a Java developer, so what's the problem here?
John Kraft
I'm not a C# developer, so what's the syntax here? :P
Zarkonnen
python does this too with raise
Dan D
+47  A: 

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.

Ogre Psalm33
"Why the compiler(s) could never figure that out and give me a proper error message" -- Include files do not have to be compilable on their own. Their contents get included into the includer before the real compilation starts.
Windows programmer
@Windows programmer - that's no excuse, really. These compilers do wonderful things already, adding another reasonable error message for a common occurrence doesn't seem out of character for them.
Tanktalus
Or at least a warning? Intentionally omitting the semicolon at the end of an include is far, far less common than doing it accidentally.
Ben Blank
Yes, a warning would be nice.
j_random_hacker
VC++ warns you if the semicolon is missing at the end of a class definition.
Ferruccio
+13  A: 

(C#) The \x escape. Quick, how different are "\x9Good compiler" and "\x9Bad compiler"?

Jon Skeet
Yeah, no kidding. Wart on the specification. Always use \u instead.
Doug McClean
Yikes. I'm very glad I've never encountered that, though it's only a matter of time.
Robert Rossney
When inheriting from C: if broken it is, fix it you shouldn't.
Windows programmer
I always use \x08 to avoid that.
Joshua
In CSS, the spec designers were thoughtful enough to make all the character escapes unicode, case insensitive and variable length up to 6 digits... so you end up with no choice but to write "\u000008Bad".
Ant P.
@Joshua: That wouldn't help in C#. "\x08Bad compiler" still isn't just a tab and then "Bad compiler". It's U+08ba and then "d compiler".
Jon Skeet
I hereby correct Jon Skeet: It still wouldn't be a tab!
jnylen
@jnylen: Oops... should have been 9 of course. Fixing.
Jon Skeet
+7  A: 

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.

Kris
+22  A: 

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...

Airsource Ltd
What compilers are you exactly using? (VS 200x and GCC x.y)
Cristian Ciupitu
And either the function is badly named or the comment is the wrong way around? :-)
Douglas Leeder
Are you sure that the comment should be continued if the '\' is followed by a space? According to the standard, the '\' is a line continuation only when immediately followed by a newline. Either way though, comments continued via a trailing '\' are evil.
Michael Burr
Good point Michael - though C99 says it's implementation defined, so in fact both are correct. I was just looking at the GCC docs when I wrote the original answer (now edited).
Airsource Ltd
What flags are you using for GCC? I got a nice big "<stdin>:1:1: error: multi-line comment" with -Wall -Wextra -Werror
Chris Lutz
+13  A: 

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.

Trap
Can you please explain what this is about?
The flow never made it into the switch statement as I was declaring another local variable which was never properly initialized.
Trap
"switch( int a )" doesn't compile, though. "switch( int a = 5 )" does.
Antti Sykäri
Yeah it does not compile now but it did at the time, and I don't even remember the compiler showing any warnings either. I'm talking about 10 years ago so we were probably using VS2004.
Trap
@Trap - welcome to our time traveling visitor from the future!
Michael Burr
"welcome to our time traveling visitor from the future!" haha
Niyaz
+2  A: 

I go from classic ASP to C# all day

Dim index = 1
Marshall
A: 

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".

Bill K
This is all I get:NameError: undefined local variable or method `bill' for main:ObjectHow did you generate the above log, and what gotcha does it represent?
Joshua Swink
Ok, I got it. Every "Bill" is supposed to be capitalized, so you're referencing two variables - one "Bill" and one "Bi11".
Joshua Swink
Yes, joshua. I don't know how I screwed up the capitalization. Fixed now. And usually this happens more with letter transpositions that are hard to see, not something as obviously tricky as replacing an l with a 1.
Bill K
I'm not sure why this is a bug. Yes, you have to be careful when you don't have to explicitly define variables. Is the solution "let bill = 5" so the "bi11 = bill + 5" throws an error?
rik.the.vik
Yes, that's the solution. To explicitly create variables instead of creating them on the fly. If you are just fooling around scripting stuff at home, that's one thing--but in a professional development environment that's just too hard to find and to easy to do.
Bill K
+8  A: 

The most annoying syntax gotcha in Perl:

my $value=something() if ($condition);
asjo
This is now a syntax error in 5.10
dland
I'm looking forward to 5.10 being standard on all the machines I use. Helloooo lenny!
asjo
I thought I was pretty good at Perl, but I'll need this one explained. It doesn't seem to elicit any unexpected behavior.
Joshua Swink
The "if" applies to the entire statement, including the "my", leading to bizarre results. When used in a subroutine or loop, if the if fails, the last invocation's value is still present, because the "my" fails to force the variable to be uninitialized.
Adam Bellaire
"my $static if 0" is (was) a common idiom, though it's been heavily discouraged for a long time now. With 5.10 finally breaking it, the fun is over...
ephemient
This is not broken in 5.10. There is actual syntax ("state $foo"), but "my $foo if 0" still works fine.
jrockway
+11  A: 

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)

  1. Calling function Foo, and passing in the argurment Bar
  2. Accessing the element at position Bar, from the array Foo.
  3. Calling function Foo, which returns an array, and accessing the element at position Bar
Kibbee
never looked at it in terms of point 3...interesting.
dotjoe
That's… horrifying.
Ben Blank
What happens if you create function Foo that takes an integer parameter and returns an array and call it with `Foo(3)`?
Wayne Werner
It assumes that you are calling the function Foo and passing 3 in as the integer parameter. Because it would be invalid to call the function without passing the parameter, it assumes the code is valid. Now, if the parameter was optional, I think it would still assume that you are passing it in as a parameter.
Kibbee
+14  A: 

In Java:

if (someString == "Y"){
  ... never executes this code, even when someString.equals("Y") ...
}
Georg Zimmer
constant gotcha, coming from the .NET world...
Michael Petrotta
Useless Trivia: It should work if someString's value was defined in the same class file as the code being executed (the compiler should be putting both instances of "Y" in the same constant pool). String someString = "Y"; if (someString == "Y") { // this works }
Adam Paynter
The fact that this sometimes works makes it worse.
No, it doesn't. It doesn't change the fact on how the "==" operator works. The String.equals is a method, the "==" is an operator testing for same values (where values is the reference when talking about objects). Though, had String used Flyweight, it would always work. And it should've.
Pål GD
+2  A: 

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
Ken
Am I right in thinking that the function in the If statement should be testString() rather than test() ?
Hamish Downer
I love how Microsoft calls this a Feature: http://support.microsoft.com/kb/817250 - "you can use this Visual Basic 6.0 feature to perform some processing that must always be completed". Ouch.
Michael Stum
A: 

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
Chad Braun-Duin
Best solution to that problem is stop using cursors in t-SQL.
HLGEM
+2  A: 

Java:

String s = "a1";
s.replaceAll("a","b");
//expect s to become "b1"
serg
+19  A: 

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, ] )

John Fouhy
also relevant when writing enumerations in C and C++ where the same problem (and solution) applies :)
workmad3
This never bothered me until I started working in JavaScript. It took me nearly an hour the first time to figure out why IE choked on my code but nothing else did…
Ben Blank
@Ben: Hell yes, every single time with IE... :-(
christian studer
It's the same with Perl too.
Rob K
Lua also allows a comma after the last entry.
Boojum
There's a dark corner of hell reserved for IE and not accepting trailing commas (among it's other injustices against dev-kind).
tj111
C++ doesn't like final commas for it's enums on some Linux compilers. But it's fine in Visual Studio's. This has caused annoyances galore.
deworde
+3  A: 

The easily forgotten global keyword in Python.

counter = 0
def increment():
    counter += 1
"Namespaces are one honking great idea -- let's do more of those!"
Johan Buret
At least this will give you an error at compile time instead of e.g. failing silently by creating, incrementing, and destroying a local variable.
John
A: 

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() {

}
Feet
+1  A: 

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.

Valters Vingolds
With VC++, The first error generated ends with: Did you forget a ';'?
Ferruccio
+2  A: 

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!

pezi_pink_squirrel
Works fine in newer compilers, though.
Constantin
@Constantin, what compiler are you smoking? Isn't this in the C++ spec?
strager
C++0x officially fixes this little wart. Nice injection of "compiler" into a common slang phrase BTW :)
j_random_hacker
+10  A: 

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?

Mark Baker
I did it one day when I had a cold. Caught it a few days later. That was just one of several instances that taught me a lesson: programming while sick yields negative productivity.
Windows programmer
Not ages - last time I did that typo was yesterday, and splint gave a 'statement has no effect' error.
Pete Kirkham
I even submitted a SO question about this recently because I went mad debugging it, only to feel like an idiot after. http://stackoverflow.com/questions/941035/arrayfilter-filtering-out-entire-array
tj111
+1  A: 

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...

Bratch
+1  A: 

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 ==

Slace
+1  A: 

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...

Claudiu
A: 

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();
}
Nazgob
+5  A: 

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).

Ates Goral
+8  A: 
#define DEBUG 1;
morsch
+1  A: 

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.

Cliff
A: 

Here's one of my favorites:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
   <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.

Cliff
A: 

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...

PhiLho
+9  A: 
DELETE FROM customers;
// without where
damian
Once I forgot to add a `WHERE subscription = 1` to my query while sending a newsletter, needless to say that some of my customers were kinda annoyed. =\
Alix Axel
That's why we have International Backup Awareness Day :P
LeguRi
That is what got me using BEGIN and END transactions...
Wayne Werner
I'm kinda busy right now, can we do International Backup Awareness Day sometime tomorrow?
Ian Mackinnon
A: 
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.

Andrew G. Johnson
+16  A: 
  1. Octal numbers in C (and some other languages).

    if(42 != 042)
        printf("WTF?!");
    
  2. 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.

IMil
In Haskell, octal literals start with 0o (zero-oh), for consistency with hex literals which start with 0x (zero-ex), which nicely avoids the first issue...
ephemient
+1  A: 
Joshua
A: 

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...

Mike Hofer
+7  A: 

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]
Gregg Lind
I've been bitten like that by initializers in a class.
porneL
The corollary is `L = [[0]*3]*3 #init 2d array; L[0][0] = 3; print L #Whoops!`
Wayne Werner
+4  A: 

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.

Rob
+2  A: 

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.

A: 
msg1     db        "The int is"
mov      eax, msg1
call     print_string
mov      eax, [intvar]
call     print_string
+1  A: 

Classic error in python:

return something,

Damned tuples.

Herge
Yeah, that tuple notation is nice and vague. I'd rather there was just a tuple(a, b, c) each and every time. Maybe there is. :)
rik.the.vik
Worse, during printf stuff: "%s %s" % "a", "b"... blows up!
Gregg Lind
it should always be "%s %s" % ("a", "b") although
Dan D
+2  A: 

In OCaml:

let mylist = [1, 2, 3];

(* How many elements does this list have? *)

Hans Nowak
How many *does* it have? The suspense is awful!
Gregg Lind
:D This one tends to bite me a lot because [1, 2, 3] is a list of three elements in Ruby, Python, SML, etc. But in OCaml it's equivalent to [(1, 2, 3)].
Hans Nowak
so what is it? one element with a 3 element turple?
acidzombie24
it seems that OCaml uses ; as the list separator and , for items in a tuple
Dan D
That... seems retarded. And I sincerely mean that. Maybe they had a good reason?
Wayne Werner
A: 

Erlang..

1>1 + 2

Nothing happns... if u dont put a "." at the end !!

+1  A: 

blah.toString() if blah is a byte array. The result you get will be a pointer to the array of bytes rendered as a string. This is never what you want. What you want is new String( blah )

+1  A: 

(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"
btucker
+1  A: 

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? :)
Because someone thought it was a good idea to declare b a static var? :PYeah, friend of mine ran into that problem in natural language processing class...
Calyth
+1  A: 
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.

A: 
for(int i=100; i>0; ++i){
 // do something
}
+25  A: 
// double-loop:
for(int i=0; i<10; ++i){
  for(int j=0; i<10; ++j){
    // do something
  }
}
If I had a stock option for every time I've done that....
David Thornley
Had this once. Luckily - only once.
Arnis L.
I'ts only a problem when you're incrementing I instead of j or something in the second loop.
RCIX
Yes i've done that, multiple times i think...
RCIX
so annoying. Copy/paste FTL
rlbond
Good thing i and j are so easy to visually distinguish eh! Using ii and jj helps with this one.
Gregg Lind
YES! I almost felt physical pain reading this. I've only done this a few times but those few times have caused me to lose much time, sleep, and sanity.
Dinah
A: 

In a shell script, having a blank after a backslash at the end of the line. It's caught as an error, but you're like: WTF, there is nothing wrong! since the blank is not visible.

+3  A: 

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);
alanwj
A: 

Errors that that complains about class Foo when I didn't include Foo.h...

Calyth
A: 

Forgetting the damn virtual destructor in a C++ abstract base class, so that later the destructors of my derived objects are not called.

A: 

In a C++ implementation file, forgetting the class name specifier for a member function:

// foo.h file
class Foo {
  void doIt();
};

// foo.cpp file
#include "foo.h"
void doIt(){
  // doing it here
}
A: 

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
rik.the.vik
This is the popular one! We now have this gotcha on here 3 times :)
Gregg Lind
A: 

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'

JohnFx
A: 

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();
John Murano
A: 

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
Trevor Bramble
A: 

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.

Thomas Padron-McCarthy
The multiline comment style seems to be going out of style, that's why. Besides, even rudimentry syntax highlighting will catch that one.
Joshua
A: 

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) { }
}
Ekevoo
A: 
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?

Dolphin
+2  A: 

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...

Carl Manaster
This is why I *always* comment when I'm using fall-through from one code-block to the next.
staticsan
+2  A: 
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.

nbv4
suing or using? ;)
Wayne Werner
A: 

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.

Konamiman
A: 
typedef unsigned char UINT8;

void Foo( void )
{
    UINT8 i;

    for( i = 0; i < 256; i++ )
    {
     // Do something
    }
}

Oops! - It's an infinite loop

Vadakkumpadath
A: 
int i=0;

NSLog(@"%@",i); //getting too used to printing out objects, compiles but manifests a EXC_BAD_ACCESS
Luke Mcneice
+1  A: 

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 [].

Hungary1234
A: 
#!/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.

Wayne Werner
A: 
int i = 0;
bool converged = false;
do {
  // std::cerr << "Iteration " << ++i << std::endl;
  converged = doSomething();
} while(!converged && i < maxiter);