Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

05 November 2011

What the IF?

If you had these both if conditions, what would you choose to put in your code?

The one:
if(rc == STATUS_SUCCESS)
{
    doSomething();
}

The other:
if(STATUS_SUCCESS == rc)
{
    doSomething();
}


Intuitively, the answer would be (rc == STATUS_SUCCESS), but! What if you forgot one = and wrote (rc = STATUS_SUCCESS) instead? This will be an assignment inside the condition, which will compile, but definitely not what you want to. Now look at the the second option, if you wrote (STATUS_SUCCESS = rc), this will not compile (since STATUS_SUCCESS  is a const) and you'll know you've a bug in compilation.

Note1: you may say: it's not gonna happen to me, I won't forget that =. But believe me, you will forget it and if you didn't go with the second option, you'll be up all night searching for that = (like I did).
Note2: using a Static Analysis Tools (aka Lint-like tools) can expose an assignment within an if-condition warning.

19 October 2011

Threads Question

I heard a question this week, and I thought it would be nice sharing it here, I did solve it, however, I'm not 100% sure I did it right :), so here it is:
What is the maximum value the variable i can get in each case below, assuming that it's a global int initialized by zero (int i=0) and the code in each case is running on 2 threads?

case1:
while(i < 1000)
{
    i++;
}
case2:
while(i < 1000)
{
    ++i;
}

case3:
while(i++ < 1000);

case4:
while(++i < 1000);

19 July 2010

99 Bottles of Beer in 1342 different programming languages

99 Bottles of Beer is a popular easy-to-memorize song to sing on long trips to pass some time. This site includes programs in 1342 different programming languages that simply generates the lyrics of this song.

The JS version is cool :-)