Loud ramblings of a Software Artisan

Sunday 28 August 2011

I hate hardware

My Linux server rebooted spontaneously and then decided to kernel panic.

Running memtest off a bootable Gnome 3 Live USB system:

Diagnosis: dead RAM stick. With only one stick, memtest even crash on test 6, while the other just pass.

The good news is that the motherboard support single channel. The second good news is that it is lifetime warranty. Requested a RMA.

The bad news: I might have to return both as they are paired leading to eventually a longer downtime. :-/

A case for braces

I am one of those who believe C and C++ should have made curly braces mandatory.

Recent version of gcc and other compiler emit a warning when you have the following:

if(foo)
  ;

It does it because you could do something like

if(foo);
{
  // do something for foo
}

And this is likely a bug. But imagine the following case:

if(foo)
  DEBUG_MESSAGE("foo");

Now you have DEBUG_MESSAGE() defined as a macro that is empty in non-debug (you don't want these for your users). Then you end up with the warning for the situation above when doing your builds. There would be no problem had you written it this way:

if(foo)
{
  DEBUG_MESSAGE("foo");
}

Also another case:

if(foo)
  if(bar)
    do_bar();
else
  dont_foo();

Do you see the bug? That's right, the code is wrong: dont_foo() is executed in the else case for if(bar). Had you put curly braces it would have been clearer of what is happening. Like that:

if(foo)
{
  if(bar)
  {
    do_bar();
  }
}
else
{
  dont_foo();
}

Also if you find this a bit too hard because of the many like, can write with that style of bracing:

if(foo) {
  if(bar) {
    do_bar();
  }
}
else {
  dont_foo();
}

The opening brace at the end of the opening statement.

Another case:

if(obj)
  obj->data->foo = 1;

Now you know that data can not be null and want to catch it when testing. So you add one line:

if(obj)
  DEBUG_ASSERT_NOT_NUUL(obj->data);
  obj->data->foo = 1;

Oops. Did you realize this is wrong? Mistakes happen. Mistakes can be prevented. Curly braces would have prevented it.

Note: in the code above you should still ensure that obj->data is not NULL before dereferencing, but that's a different subject, for another time.

Bottom line, don't be lazy. Make the use a curly braces mandatory in your coding style. If your compiler has a warning for that, enable it.