...

/

Initialize Compound Types with `0`

Initialize Compound Types with `0`

In this lesson, we will briefly explain the idiom "Initialize Compound Types with `0`".

We'll cover the following...

Problem Context

Virtually every coding standard bans uninitialized variables, and for very good reason. Initializing a basic type such as int or char is straightforward, but what is the correct way of initializing a compound type like an array or struct? A dangerous but unfortunately common practice is shown below:

Press + to interact
#include<stdio.h>
#include<string.h>
struct TemperatureNode
{
double todaysAverage;
struct TemperatureNode* nextTemperature;
};
int main() {
struct TemperatureNode node;
memset(&node,0, sizeof node);
printf("Node created\n");
return 0;
}

The problem is that memset, as its name indicates, sets the bits to the given value and ...