share
Stack OverflowWhat is your (least) favorite syntax gotcha?
[+58] [91] Goran
[2008-10-02 15:30:33]
[ syntax polls ]
[ http://stackoverflow.com/questions/163026] [DELETED]

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.

(1) close discussion question, not a programming question. - Mark Rogers
(2) o.O, It's not argumentative, I give you subjectve, and it's very much about programming. - Filip Ekberg
Oh and if you want to know how this might be helpfull, well new coders do errors all the time, if they read this question page to page they might end up not have to suffer.. :) - Filip Ekberg
(2) It says "Is your question about programming? We prefer questions that can be answered, not just discussed." in the ask a question page. This is a question that can only be discussed. - Mark Rogers
m4bwav, we can always make exceptions. If we all start closing questions for silly reasons, SO will not be fun anymore. - Niyaz
(24) Is anyone else fighting the urge to go through and fix the syntax and bugs on these answers? :) - Bill the Lizard
I'm not voting to close, but I'm downvoting for suspected reputation trolling. - Carl Smotricz
(2) It's community wiki - I suspect you've missed that Carl :) - Goran
[+195] [2008-10-02 15:32:13] Bill the Lizard [ACCEPTED]
if (status = UNDER_ATTACK) {
    launch_nuclear_missiles();
}

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
(2) @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. - Sean Hanley
Oh lordy this one is insidious. - Magsol
(10) 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
(9) 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
(6) @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
(2) 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
(4) @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
@Daniel Rose - An alternative would be to use ` if ((value = get_value_one_way()) != 0) { ... }` instead and leave the warning turned on ;-) - msp
@msp That's true, but that means we would have to "fix" those thousands of places, which means quite some time spent. - Daniel Rose
1
[+109] [2008-10-02 15:31:42] Goran

I was stumped by:

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

But the compiler warning proved very helpful!


(10) This has caused almost as many headaches as missing semicolons. - Bill the Lizard
(29) 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
(3) @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
(15) another great reason to use the one true brace style! huzzah! - nickf
(1) @goran.siska.myopenid.com: ECMAScript (aka JavaScript) automaticly adds Semicolons (in certain situations) see §7.9 :-) - jk.
(1) @nobody: you would´t. you could do while (*p++ = *q++) {}; - Leonel Martins
(3) 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
2
[+72] [2008-10-02 15:55:11] twk

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

(39) 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. joelonsoftware.com/articles/Wrong.html - Sean Hanley
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
(4) to me, doing this: if(x) { foo(); } instead of this: if(x) foo(); is the same thing as doing this: x = (y+z); instead of x = y+z; it's unecessary and ugly. - Kevin
(7) 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
(12) 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
(4) Bah. A better rule is to not make this mistake. Braces for single-liners is ugly. - rlbond
3
[+72] [2008-10-02 15:59:32] JaredPar
int* y,z;

This is just a failing of the language :(


(7) another good reason why declarations should be on their own line - Joe Philllips
Wow, no kidding. This always annoys me. - twk
(26) This is a good reason to switch to the convention of: int *y,z; - Wedge
(10) @Wedge: and the reason to stick with type* is "The star (*) (or reference (&)) is a modification of the type and not the name. That's the /cool/ thing about C/C++ you can argue about so much useless things :-) - 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 S.
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
(1) The rationale is the following: If the * was tied to the type (int* x), the star would have two meanings: 1) pointer of type int, (int*) and 2) what x points at (*x)... By tying it to the identifier (int *x) it means the same everywhere, since int *x now would read out as, I declare an int located wherever x points at. - aioobe
4
[+65] [2008-10-02 16:00:49] Jon Skeet

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


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 Krall
Ha, C++ lets you call instance methods on null, as long as you cast it to the right type! - user4891
(10) 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
@Michael Burr: it should just have a different syntax, for example t::sleep(1000) would be fine. - 7vies
@7vies: What benefit does that give over simply not allowing it? - Jon Skeet
@Jon Skeet: I don't know for Java, but in C++03 it is not allowed while I would use it to define iterators as container::iterator instead of having to look for the actual container type and writing container_class::iterator. I imagine that there could be similar uses in Java or wherever. Another option is gcc's typeof which allows to write typeof(container)::iterator. - 7vies
@7vies: Whereas I'd rather make the actual type explicit, to make it clear that the value of the variable is irrelevant. - Jon Skeet
@Jon Skeet: I see your point, but a variable is not just a (value) - it is a pair (value, class), and it would be fair to be able to use the class part, not the value part only. Note the typeof update to my previous comment. - 7vies
@7vies: Where else does referring to a variable actually refer to only its class rather than being associated with its value? - Jon Skeet
@Jon Skeet: If I got your question right - for example, in generic (C++) programming it is quite common to behave differently depending on the variable class, while the value might not be used at all, or used at some later time. - 7vies
@7vies: Maybe that's just a difference between Java and C++ then... I can't think of any other situations where in Java where the value of the variable is irrelevant. - Jon Skeet
@Jon Skeet: Well, in C++ it is not very much required neither unless you try to make macros be type-dependent (I would say a kind of templates emulation), as the type of the variable is static. However, I think it can still be handy in either language, because you don't have to look for the type of the variable (which can be defined in some other file as a base class member for example). Also, when you write var::something you can change the variable type later, and this would imply the change of the something that is called - but this might be dangerous, and is usually done using typedef - 7vies
5
[+59] [2008-10-02 16:22:35] Ogre Psalm33

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.


(1) "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
(6) @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
(1) VC++ warns you if the semicolon is missing at the end of a class definition. - Ferruccio
(2) Having to add a semicolon after a closing brace is very untypical for C, it's annoying and a constant source of error. It is caused by a language misdesign of the original Kernigan and Richie C language: When declaring a struct, you can optionally define a variable of this type in the same statement. So the semicolon is necessary to distinguish between class Foo {...}; and class Foo {...} foo; What a superfluous shortcut! I consider it bad style to stuff two loosely related declarations into one statement and would rather do without this feature! - msp
6
[+57] [2008-10-02 15:35:36] Forgotten Semicolon

Should be obvious from my name. Forgotten Semicolon.


That used to be my (least) favorite thing to explain to my boss. - Bill the Lizard
(6) Upvoting for the name reference. - leek
(17) Oh man, I love getting 100 compiler errors, none of which actually point to where the mistake is. - andy
(1) 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
(1) @MrValdez: Done! - Forgotten Semicolon
upvoted. I would have been in a jail by now. - Mohamed
Answer remains valid for those of us who use SAS @YKtula A better compiler is not an option for SAS. Although a good comeback would be: "Try using R". But that is beside the point. I <3 @Forgotten Semicolon on general grounds. Very nice sense of humor everywhere. - Feral Oink
7
[+39] [2008-10-02 15:37:42] Robert
if( x & 3 == 1)
{
    // This will never be run.
}

I've spent hours debugging things like this... - rmeador
I think I've confused myself (reading a page full of syntax gotchas will do that to you). Does this not just check that the first bit in x is set? Don't & and == evaluate left-to-right at the same precedence? - SpoonMeiser
== is one step higher than &. So the result is: if( x & (1 == 1) ) - Robert
i'm probably wrong, but isn't (x & (1 == 1)) the same as ((x & 1) == 1)? I mean, one's an int and the other a bool, but they're both true, right? - nickf
Maybe, but what if it's if (x & 2 == 2) ? I think that was the point, but with a poor example. - Bdoserror
Better written as if(x % 2 == 1), I think. - Cristián Romo
x & 2 == 1 is always going to evaluate false, no matter what the order of precedence. x % 2 == 1 doesn't suffer from the surprising precedence issue. x & 3 == 1 could be a plausible situation. It looks like you're checking that the bottom two bits are 01, but really, it always evaluates to false. - Eclipse
(3) Unless, of course, you overload the & binary operator! - strager
@strager - that would be EVIL!! - Robert
(47) 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
(7) 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
(2) @Michael - I think it's important to also know the relational/logical/assignment precedences. I would much rather see if(x > 3 && x < 6) than if((x > 3) && (x < 6)), and who wants to see a += (b + c) honestly? Those are easy (and by easy I mean intuitive to me) and common enough that most programmers should know them. - Chris Lutz
8
[+35] [2008-10-02 15:59:17] Jon Skeet

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


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
(2) 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
@Erik Are braces ever really used for anything besides scoping? - Matt Davison
(1) @Erik: You can put braces around every code block you like. - VVS
(2) @Erik: you can add braces to anything. This is legal: if(foo) {{{{bar();}}}} - Zifre
(8) @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
9
[+35] [2009-01-30 22:28:44] Frank
// double-loop:
for(int i=0; i<10; ++i){
  for(int j=0; i<10; ++j){
    // do something
  }
}

(6) If I had a stock option for every time I've done that.... - David Thornley
(2) Had this once. Luckily - only once. - Arnis L.
(1) I'ts only a problem when you're incrementing I instead of j or something in the second loop. - RCIX
(1) Yes i've done that, multiple times i think... - RCIX
(2) 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
10
[+34] [2008-10-02 15:49:48] Garth Gilmour

In C++

Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype

(7) 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
I dont get it :( - Shawn Mclean
(1) @Shawn: the code fragment above declares 2 variables (or instances), named e1 and e2, whose type is Employee. e3, however, is a 'function prototype' of a function that takes no argument and returns an Employee. - René Nyffenegger
(1) @rlbond : There are so much examples of functions (or other symbols/types) declared/defined in function I don't know where to start the list. Let's ignore Pascal, Java, C#, and play with C . . . In C, you can declare and use a struct inside a function (which, in itself, could seem strange) . . . For C compatibility, C++ authorizes this . . . But as a C++ struct can have methods, it means you can in C++ define inside a function A a struct B with a static method C, effectively making this method C a function inside a function A . . . I already used that technique in production code. - paercebal
11
[+28] [2008-10-02 16:07:27] harriyott

Forgetting a MoveNext in a classic ASP recordset loop

while rs.EOF = false
    Response.Write rs("name")
wend

(2) 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
(1) I did something like that so many times I actually put a sticky note on my monitor that said "rs.MoveNext". - Corin
12
[+27] [2008-10-02 17:03:02] Airsource Ltd

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


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
[+26] [2008-10-02 15:39:17] davetron5000
public class FooHolder
{
  private String foo;

  public void setFoo(String foo)
  {
    foo = foo;
  }
}

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
(2) 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
(1) 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
(7) 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
14
[+25] [2008-10-03 02:24:57] John Fouhy

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


(3) also relevant when writing enumerations in C and C++ where the same problem (and solution) applies :) - workmad3
(2) 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
(1) It's the same with Perl too. - Rob K
(1) 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
15
[+19] [2008-10-02 15:40:27] Joe Philllips

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.


(4) 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
(2) 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
takes note Idea: esoteric programming language where null object can be overridden. Just for the lulz. - Alpha
16
[+17] [2008-10-02 18:06:51] Georg Zimmer

In Java:

if (someString == "Y"){
  ... never executes this code, even when someString.equals("Y") ...
}

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
(15) The fact that this sometimes works makes it worse. - user4891
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
17
[+17] [2008-10-02 16:11:46] James Schek

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

I'm not a Java developer, so what's the problem here? - John Kraft
(1) I'm not a C# developer, so what's the syntax here? :P - Zarkonnen
(1) python does this too with raise - Dan D.
18
[+17] [2008-12-24 16:29:28] IMil
  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.


(1) 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
19
[+15] [2008-10-02 16:27:10] Jon Skeet

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


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
(1) 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". - flussence
(1) @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
(6) Is there a "Corrected Jon Skeet" badge? :) - kirk.burleson
(4) @kirk: we only have badges up to gold. - progo
20
[+15] [2008-10-02 17:19:46] Trap

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.


(1) Can you please explain what this is about? - community_owned
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
(3) 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
(14) @Trap - welcome to our time traveling visitor from the future! - Michael Burr
"welcome to our time traveling visitor from the future!" haha - Niyaz
(1) VS2004? Didn't Microsoft publish some "Missing" posters with a reward$$$ for anyone helping them locate this compiler some time ago... Are you the kidnapper? - paercebal
21
[+14] [2008-10-02 17:55:52] Kibbee

This post of mine [1] 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
[1] http://stackoverflow.com/questions/142697/vbnet-function-that-returns-string-only-returns-single-character

never looked at it in terms of point 3...interesting. - dotjoe
(7) That's… horrifying. - Ben Blank
(1) What happens if you create function Foo that takes an integer parameter and returns an array and call it with Foo(3)? - Wayne Werner
(1) 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
22
[+14] [2008-10-02 15:38:18] Dana

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.


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). - flussence
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
23
[+14] [2008-10-03 09:40:41] Mark Baker

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?


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
(4) I even submitted a SO question about this recently because I went mad debugging it, only to feel like an idiot after. stackoverflow.com/questions/941035/… - tj111
24
[+12] [2008-12-03 01:18:11] damian
DELETE FROM customers;
// without where

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
(3) That's why we have International Backup Awareness Day :P - Richard JP Le Guen
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
25
[+10] [2008-10-18 13:17:17] morsch
#define DEBUG 1;

26
[+8] [2009-01-30 14:16:53] Gregg Lind

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]

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
27
[+8] [2008-10-02 17:55:36] asjo

The most annoying syntax gotcha in Perl:

my $value=something() if ($condition);

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
(1) "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
28
[+8] [2008-10-02 16:29:47] Kris

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.


29
[+6] [2008-10-18 13:02:14] Ates Goral

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 [1] helps).

[1] http://www.jslint.com/

I've seen this so much that now I use IE6 as my second compiler. - Alpha
30
[+5] [2009-01-30 14:26:03] Rob Z

In Visual Basic and Visual Basic for Applications, IIf [1] 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.

[1] http://msdn.microsoft.com/en-us/library/27ydhh0d(VS.71).aspx

31
[+5] [2009-01-30 23:56:02] alanwj

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

32
[+4] [2009-01-30 17:31:40] Hans Nowak

In OCaml:

let mylist = [1, 2, 3];

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


How many does it have? The suspense is awful! - Gregg Lind
(1) :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
(1) it seems that OCaml uses ; as the list separator and , for items in a tuple - Dan D.
(3) That... seems retarded. And I sincerely mean that. Maybe they had a good reason? - Wayne Werner
33
[+3] [2009-01-30 14:49:28] community_owned

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.


34
[+3] [2008-10-03 09:16:10] pezi_pink_squirrel

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!

This has been rectified in C++0x.


Works fine in newer compilers, though. - Constantin
@Constantin, what compiler are you smoking? Isn't this in the C++ spec? - strager
(3) C++0x officially fixes this little wart. Nice injection of "compiler" into a common slang phrase BTW :) - j_random_hacker
35
[+3] [2008-10-03 04:21:59] community_owned

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
36
[+3] [2008-10-02 17:44:41] Marshall

I go from classic ASP to C# all day

Dim index = 1

37
[+3] [2008-10-02 15:52:41] Goran

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

DELETE Users
SELECT *
FROM Users u
WHERE u.Reputation > 10000

That's not really a syntax problem so much as having a basic misunderstanding of the language. - Joe Philllips
(1) 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
(1) By the way, nice example. - kbrinley
DELETE FROM students; WHERE students.reg_date < '2008-09-01'; - community_owned
38
[+3] [2008-10-02 16:03:22] JayG

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

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

I've spent hours not finding that...


39
[+2] [2008-10-02 15:42:42] polara

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.


40
[+2] [2008-10-02 15:41:07] Patrick Desjardins

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


41
[+2] [2008-10-02 18:17:40] Ken

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

(1) Am I right in thinking that the function in the If statement should be testString() rather than test() ? - Hamish Downer
(1) I love how Microsoft calls this a Feature: 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
42
[+2] [2008-10-02 16:08:23] Ryan

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?


(1) Oh, you'd /love/ Perl... - SpoonMeiser
43
[+2] [2008-10-03 00:27:19] serg

Java:

String s = "a1";
s.replaceAll("a","b");
//expect s to become "b1"

44
[+2] [2008-10-03 07:35:12] Valters Vingolds

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.


With VC++, The first error generated ends with: Did you forget a ';'? - Ferruccio
45
[+2] [2008-10-03 21:46:29] Bratch

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


+1 cause I just felt your desperation only reading the story... I could have just die in stress and never finding that. - Alpha
46
[+2] [2009-06-02 20:24:05] Carl Manaster

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


(1) This is why I always comment when I'm using fall-through from one code-block to the next. - staticsan
47
[+2] [2009-06-12 22:21:07] nbv4
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.


suing or using? ;) - Wayne Werner
48
[+1] [2010-08-05 17:58:56] Hungary1234

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


49
[+1] [2011-06-28 18:39:30] msp

Did you ever stumble over this one?

printf("Are you kiddin??!");

One million dollar question: what do you get to see in the output? (You might like to use the WikiPedia-Joker [1] ;-)

[1] http://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C

50
[+1] [2008-10-03 22:05:41] Slace

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


51
[+1] [2008-10-06 23:25:00] Claudiu

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


52
[+1] [2008-12-24 17:12:08] Joshua

<script runat="server">
Response.Write("<script>")
Response.Write("...")
Response.Write("</script>")
</script>

Scratch my head when the IDE barfs.


53
[+1] [2008-10-18 13:23:45] Cliff

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.


54
[+1] [2009-01-30 17:20:24] Herge

Classic error in python:

return something,

Damned tuples.


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.
55
[+1] [2009-01-30 21:14:51] community_owned

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 )


What language is this? - Mechanical snail
56
[+1] [2009-01-30 21:42:00] btucker

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

57
[+1] [2009-01-30 21:46:49] community_owned

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? :P Yeah, friend of mine ran into that problem in natural language processing class... - Calyth
58
[+1] [2008-10-02 18:28:29] Chad Braun-Duin

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

Best solution to that problem is stop using cursors in t-SQL. - HLGEM
59
[+1] [2008-10-02 15:41:52] Garth Gilmour

Prior to Eclipse:

class Person {
    Person (String name) {
        //parameter assigned to itself as field hidden
        name = name;
    }
    private String name;
}

60
[0] [2008-10-02 15:34:55] EricBouwers
if(calculateSomething()){
   return true;
}
else {
   return false;  
}

you should get a syntax error for this one ... the else do not correspond to any if ! - PierreBdR
(1) what? I don't see any problem here, am I blind? - fijter
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
61
[0] [2008-10-02 15:45:22] George Mauer

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


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
62
[0] [2008-10-02 15:45:55] George Mauer

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


63
[0] [2008-10-02 16:07:01] Fry

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


64
[0] [2008-10-02 17:52:50] Bill K

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


This is all I get: NameError: undefined local variable or method `bill' for main:Object How 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
65
[0] [2009-01-30 22:20:13] community_owned
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.


Conceptually, the (a*100)/b is evaluated before assignment to c, so expect it to overflow. - Mechanical snail
66
[0] [2009-01-30 22:25:40] Frank
for(int i=100; i>0; ++i){
 // do something
}

67
[0] [2009-01-30 23:57:15] Calyth

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


68
[0] [2009-01-31 00:03:02] Frank

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


69
[0] [2009-01-31 00:05:08] Frank

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
}

70
[0] [2009-01-31 00:34:49] rik.the.vik

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

This is the popular one! We now have this gotcha on here 3 times :) - Gregg Lind
71
[0] [2009-01-31 01:04:24] JohnFx

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'


72
[0] [2009-01-30 18:49:20] community_owned

Erlang..

1>1 + 2

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


73
[0] [2008-10-18 13:37:27] Cliff

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

[1] http://codeforfun.wordpress.com/2006/11/21/javautilemptystackexception/
[2] http://www.google.com/search?sourceid=mozclient&ie=utf-8&oe=utf-8&q=java%2Eutil%2EEmptyStackException

74
[0] [2008-11-07 22:24:19] PhiLho

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


75
[0] [2008-12-24 17:26:08] Mike Hofer

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


76
[0] [2008-10-18 11:46:15] Nazgob

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();
}

77
[0] [2008-10-03 04:39:46] Feet

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

}

78
[0] [2011-08-14 16:09:15] phunctor

Python

A string, less the final k bytes:

s = s[:-k]

unless k == 0


79
[0] [2010-08-05 18:57:36] Wayne Werner
#!/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.


80
[0] [2010-09-28 16:04:32] Frank
int i = 0;
bool converged = false;
do {
  // std::cerr << "Iteration " << ++i << std::endl;
  converged = doSomething();
} while(!converged && i < maxiter);

81
[0] [2009-01-30 22:37:58] Frank

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.


82
[0] [2009-09-25 10:27:08] Konamiman

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.


83
[0] [2009-12-27 02:52:17] Vadakkumpadath
typedef unsigned char UINT8;

void Foo( void )
{
    UINT8 i;

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

Oops! - It's an infinite loop


84
[0] [2010-07-22 12:20:08] Luke Mcneice
int i=0;

NSLog(@"%@",i); //getting too used to printing out objects, compiles but manifests a EXC_BAD_ACCESS

85
[0] [2009-01-31 03:45:52] Trevor Bramble

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

86
[0] [2009-02-09 04:07:49] Thomas Padron-McCarthy

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.


The multiline comment style seems to be going out of style, that's why. Besides, even rudimentry syntax highlighting will catch that one. - Joshua
87
[0] [2009-06-02 19:37:26] Ekevoo

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

88
[0] [2009-06-02 20:18:42] Dolphin
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?


89
[-1] [2009-01-30 17:07:38] community_owned
msg1     db        "The int is"
mov      eax, msg1
call     print_string
mov      eax, [intvar]
call     print_string

90
[-1] [2009-01-31 02:32:49] John Murano

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

91