Showing posts with label C++. Show all posts
Showing posts with label C++. Show all posts

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

Oct 21, 2009

Dangerous logging

Today I will try to scare you:)
The most common realization of logging is something like that (simplified):
#include <stdio.h>

#ifdef _MSC_VER // workaround for MS VC
#define snprintf(b, bsz, f, ...)                \
        _snprintf_s(b, bsz, _TRUNCATE, f, __VA_ARGS__)
#endif
#define LOG_LEVEL 2
#define LOG(lvl, ...) do {                       \
    if (LOG_LEVEL < lvl) break;                  \
    char b[1024];                                \
    snprintf(b, sizeof(b) - 1, __VA_ARGS__);     \
    b[sizeof(b) - 1] = 0;                        \
    printf("%i! %s\n", (int)(lvl), b);           \
} while(0 == __LINE__)