As I expect a lot of people not being convinced by what I wrote yesterday about mixing declarations and code, here comes a simple example of where my style works better than the “classic” style of not mixing them:
#include
#include
char* oldstyle(const char *foo) {
size_t foolen;
if ( foo == NULL )
return NULL;
foolen = strlen(foo);
return strdup(foo);
}
char* newstyle(const char *foo) {
if ( foo == NULL )
return NULL;
const size_t foolen = strlen(foo);
return strdup(foo);
}
(note: I should really try to find a better way to post code, possibly with syntax highlighting, if anybody knows something, please let me know).
In both these functions the foolen
variable is unused, but if you compile this with gcc -Wextra -Wunused
, it will only warn you about the one on line 19, that is, the one that is mixed in the code.
This is because foolen is being used at least once in the first function, to assign a value.
Now of course gcc is smart enough to know this and indeed the call to strlen()
is not emitted already with -O1 on both functions, but you’ll still have it in the code. I’d suppose it would be a bug that GCC doesn’t warn you in the first case, but I should ask Mike or Mark about that.
Borland sorry, Codegear’s compiler does actually warn you for this style with something alike to “variable assigned a value never used” (I don’t remember the exact wording here). Which is quite nice because it also catches the cases where a variable is declared with an initialisation, but then is set within both branches of an if
statement. Not much of a difference for basic types but it can find useless call in the thing. I think Visual C# compiler also does that, for attributes too which is quite more interesting, but there are more considerations about that I suppose.
I wonder how many of these problems are there in the source code of xine-lib and xine-ui, I’m afraid a lot more than currently gcc reports.