Reputation: 41845
I have heard a lot about the importance of programming style. In my opinion, indention is easy to deal with. But other things frustrated me a lot. Considering a particular example to demonstrate the use of inet_makeaddr.
/* demonstrate the use of host address functions */
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int
main(void)
{
/* inet_makeaddr demo */
uint32_t neta = 0x0a3e5500;
uint32_t hosta = 0x0c;
struct in_addr alla = inet_makeaddr(neta, hosta);
printf("makeaddr of net: %08x and host: %08x = %08x\n",
neta, hosta, alla);
return 0;
}
Somebody may want to write as follows:
uint32_t neta;
uint32_t hosta;
struct in_addr alla;
neta = 0x0a3e5500;
hosta = 0x0c;
alla = inet_makeaddr(neta, hosta);
Then others may always initialize the variable when defined:
uint32_t neta = 0;
uint32_t hosta = 0;
struct in_addr alla = {0};
neta = 0x0a3e5500;
hosta = 0x0c;
alla = inet_makeaddr(neta, hosta);
Is any one of these better than the other ones, or it is just a personal taste?
Upvotes: 0
Views: 769
Reputation: 2322
It is usually always better to initialise variables in any language. Somehow it's just oen of those little things that make your life easier, just like leaving a trailing comma.
Although if you are going to initialise your variables it's probably best to do it with a value that means something to your algorithm, otherwise you're not solving anything, just changing the way everything behaves when you create a bug.
Upvotes: 0
Reputation: 1322
Personally I define the variables close to the function call if they are interesting for the function call. If it is an uninteresting variable I usually define it it in the declaration.
Upvotes: 0
Reputation:
The bottom one has the small advantage that even if you change the code so that the initialization is no longer performed, you'll never have garbage in the variables, but only zeros. The top one has the same advantage though. My own preference in C is for functions to be extremely short, so that you never have to worry about those kinds of things, so I use the top form or the second form. But if your functions are long-winded, initializing everything to zero might be the way to go.
Upvotes: 0
Reputation: 56133
I think the first of the three examples is the best: the second example one has uninitialized variables, and the third example has variables initialized to a meaningless (zero) value. I prefer to initialize variables (with a meaningful value) as soon as I define them (so that I don't have uninitialized variables). See also Should Local Variable Initialisation Be Mandatory?
Upvotes: 5
Reputation: 25287
I like to initialize values when defining. At least you know you won't have any "silly" NULL reference errors.
Upvotes: 0