A coding style presentation that I attended lately in office advocated that variables should NOT be assigned (to a default value) when they are defined. Instead, they should be assigned a default value just before their use.
So, something like
int a = 0;
should be frowned upon.
Obviously, an example of ‘int’ is simplistic but the same follows for other types also like pointers etc.
Further, it was also mentioned that the C99 compatible compilers now throw up a warning in the above mentioned case.
The above approach looks useful to me only for structures i.e. you memset them only before use. This would be efficient if the structure is used (or filled) only in an error leg.
For all other cases, I find defining and assigning to a default value a prudent exercise as I have encountered a lot of bugs because of un-initialized pointers both while writing and maintaining code. Further, I believe C++ via constructors also advocates the same approach i.e. define and assign.
I am wondering why(if) C99 standard does not like defining & assigning. Is their any considerable merit in doing what the coding style presentation advocated?
Usually I’d recommend initialising variables when they are defined if the value they should have is known, and leave variables uninitialised if the value isn’t. Either way, put them as close to their use as scoping rules allow.
Usually you shouldn’t use a default value at all. In C99 you can mix code and declarations, so there’s no point defining the variable before you assign a value to it. If you know the value it’s supposed to take, then there is no point in having a default value.
Not for the case you show – you don’t get a warning for having
int x = 0;. I strongly suspect that someone got this mixed up. Compilers warn if you use a variable without assigning a value to it, and if you have:then you will get a warning that x may be used without being initialised, at least with gcc.
You won’t get a warning if you assign a value to
xbefore theif, but it is irrelevant whether the assignment is done as an initialiser or as a separate statement.Unless you have a particular reason to assign the value twice for two of the branches, there’s no point assigning the default value to x first, as it stops the compiler warning you that you’ve covered every branch.