-
Step 1
Initialize a variable in C to assign it a starting value. Without this, you will get whatever happened to be in memory at that moment, which leads to inconsistent behavior and irreproducible bugs that can be exceedingly difficult to track down.
-
Step 2
Add an initialization to the declaration. Just tack on an assignment right to the end of the declaration, like so:
int x = 5;
-
Step 3
Know that initializing arrays works similarly, save that you must put multiple comma-separated values inside curly brackets. When doing this, you can leave off the array's size, and it will be filled in automatically:
int month_lengths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; -
Step 4
Take advantage of character strings. Character strings, which are really arrays of characters, also support a simpler format for initialization:
char title[] = "My Program";
-
Step 5
Express either kind of array initialization in pointer format (since arrays are really pointers):
int *month_lengths = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
char *title = "My Program"; -
Step 6
Remember that structures in C are initialized in the same way as arrays:
struct role = { "Hamlet", 7, FALSE, "Prince of Denmark", "Kenneth Branagh"}; -
Step 1
Wait to initialize a variable at another place in the program if this will be clearer. For instance, a variable that will be the index of a for loop is usually best initialized in the for loop. This makes it easier for another programmer to read, since the initialization is near where it will be used.
-
Step 2
Initialize the data structure at the right time. If a data structure is going to be dynamically allocated with malloc() or a similar function, you can't initialize it until after it's allocated. However, in this case, what you're declaring is actually a pointer, which should still be initialized to NULL as a matter of course.











