Nov 25, 2009

The right way to check whether the C string is empty

It is:
char *s;
// .. do something with s ...
if (!*s) printf("empty!\n");
or
if (0 == *s) printf("empty!\n");
I prefer the second one, because find it easier to read, but it doesn't matter really.

The most popular bad ways to do this:
  • if (0 == strlen(s)) printf("empty\n");
  • if (0 == strcmp(s, "")) printf("OMG, empty!\n");
And it is not a joke, today I saw 2 independent reviews with such kind of stuff.

p.s. There is a popular joke about how foreign developers check bool value to be a true:
if (4 == strlen(bool2str(value))) printf("its true!\n");

Nov 8, 2009

Structure and class methods have external linkage

Lets look on small example:
File f01.cpp:
#include <stdio.h>
struct TEST
{
    TEST() { printf("TEST from f01: created\n"); }
    unsigned m;
};
void f01()
{
    TEST t;
    printf("TEST from f01: sz=%u\n", (unsigned)sizeof(t));
}
File f02.cpp:
#include <stdio.h>
struct TEST
{
    TEST() { printf("TEST from f02: created\n"); }
    unsigned m1;
    unsigned m2;
};
void f02()
{
    TEST t;
    printf("TEST from f02: sz=%u\n", (unsigned)sizeof(t));
}
File main.cpp:
#include <stdio.h>
void f01(); // prototype
void f02(); // prototype
int main(int argc, char *argv[])
{
    (void)argc; (void)argv;
    f01();
    f02();
    return 0;
}
Program output:
TEST from f01: created
TEST from f01: sz=4
TEST from f01: created
TEST from f02: sz=8

Nov 7, 2009

Top level window receives WM_GETMINMAXINFO before WM_NCCREATE

Keep in mind, that on Windows top level window receives WM_GETMINMAXINFO message prior to WM_NCCREATE. Such behavior can be fatal for application that executes window initialization code in WM_NCCREATE message handler, since when receiving WM_GETMINMAXINFO window is not initialized yet.
Oh, that cruel, stupid world...