Further adventures in C++

Posted on:February 27 2009

When I write code like

if (doSomething())    str = SOME_CONSTANT;else    doSomethingElse();

I am usually pretty sure that this works. But if the compiler then tells me

error C2181: illegal else without matching if

I really start scratching my head. Especially if it is already late at night and I need some sleep. So I sat there, sleepy, scanning these 4 lines of code for some invalid character I've typed in by accident. Do you see it?
I didn't either. Everything looks correct, right?
I finally got my sleep when I realized some CENSORED CENSORED CENSOREDhead had written this to define 'SOME_CONSTANT':

#define SOME_CONSTANT "sdfs";

But I guess programming would be boring without gems like this.





Comments:


This is why #define is evil and should not be used unless you have no other option. Static const variables or enums are a far better choice for constants.
steve
Quote
2009-02-27 14:08:00


Lol ... but #define s are a fine thing ... use it with care - like many of the "C" things I like (like the "?" operator) - and you can be happy. Use it without the care they need and you'll get error messages you won't understand.
Brainsaw
Quote
2009-02-27 15:51:00


One reason why I try to write the brackets even if there's only one statement in the if/else block.

But yeah I know... we programmers are too lazy to type in this 4 more characters ^^
Sylence
Quote
2009-02-27 16:01:00


SOME_CONSTANT is the first place I would have looked.
rbrt
Quote
2009-02-27 18:23:00


Well, use g++ next time:

bla.c:14: error: expected primary-expression before 'else'
bla.c:14: error: expected `;' before 'else'
blah
Quote
2009-02-27 18:38:00


found this once: #define FOREVER for(::)
someone obviously tried to be funny.
*grumble*
KIENI
Quote
2009-02-28 06:05:00


@grumble: Its more like this:
#define EVER ;;
...
for (EVER)
{
DoThisAndThat();
}

P.S
I find it very funny :).
MasterGod
Quote
2009-02-28 19:11:00


Before else never have ";".
ngoac
Quote
2009-03-01 05:50:00


clearly the preprocessor is not mighty enough, because it can just insert the text and not process it. SOME_CONSTANT#SUBSTR(0,$-1) or something like that would look proper ;-)
xaos
Quote
2009-03-02 12:39:00


This is why i hate the c++ programmers that come from c...
they use this CENSORED things...
why they don't use the const?!?
is better, is usefull and is not as in c :)

revan1985
Quote
2009-03-09 10:01:00


Add comment:


Posted by:


Enter the missing letter in: "Internationa?"


Text:

 

  

Possible Codes


Feature Code
Link [url] www.example.com [/url]
Bold [b]bold text[/b]
Quote [quote]quoted text[/quote]
Code [code]source code[/code]

Emoticons