What is Structure Initialization in C- Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Chapter 10 · Lecture 3

Structure Initialization in C

Brace initializers, partial initialization, designated initializers and struct copies, with tested embedded C examples.

A structure variable that has never been given a value contains garbage, and garbage in a hardware configuration is how motors spin the wrong way. In this part of our free C programming course you will learn every practical way of doing structure initialization in C: positional braces, leaving members out, naming the members you want, and copying one structure into another.

This free C tutorial also corrects a rule you will find in many old books. They say initializer values must be constants. That was true for pre-1999 compilers; modern C lets you initialize local structures from ordinary variables, a habit that makes embedded C programming much more convenient.

What You Will Learn

In this lecture:

  • Initialize a structure with a brace list in member order.
  • Predict what happens to members you leave out.
  • Use designated initializers to set members by name, in any order.
  • Copy a structure with a single assignment.
  • Explain why you cannot give default values inside the definition and read the error.

Prerequisites

Lectures 1 and 2 of this chapter: you should know how to define a structure and declare variables from it. Array initialization from the Arrays chapter helps, since the syntax is a close cousin.

The Brace Initializer

Initialization means giving a variable its value in the same statement that creates it. For structures, you write the values inside curly braces, separated by commas, in the same order as the members were defined:

struct uart_cfg {
    char     port[8];
    unsigned baud;
    int      parity;
    float    timeout_s;
};

struct uart_cfg a = { "UART1", 115200, 0, 1.5f };

The first value goes to port, the second to baud, and so on. The order and the types must match the definition. A string literal can initialize a character array member, exactly like it does for a plain array.

How values map to members

Position in bracesValueMember that receives it
1"UART1"port
2115200baud
30parity
41.5ftimeout_s

Partial Initialization: The Rest Become Zero

If you supply fewer values than there are members, the remaining members are set to zero. Numbers become 0, floats become 0.0, pointers become null, and character arrays are filled with zero bytes:

struct uart_cfg b = { "UART2" };   /* baud, parity, timeout_s are all 0 */

This leads to the most useful idiom in embedded code, the all-zero structure:

struct uart_cfg d = { 0 };

The single 0 initializes the first member, and the rule above zeroes everything else. Some compilers print a warning for this form with strict flags, such as missing initializer for field. It is harmless, and the empty-brace form = {} is available in newer C standards if you prefer it.

Watch the rule’s limit. Zeroing happens only when you provide an initializer. A structure declared with no initializer at all, such as struct uart_cfg x; inside a function, holds indeterminate garbage. Global and static variables, however, are always zeroed before main runs.

Designated Initializers: Name What You Set

Positional lists are fragile: add a member in the middle of the definition and every initializer in your code silently shifts. Since C99 you can name the members instead:

struct uart_cfg c = { .baud = 9600, .port = "UART3" };

Each .member = value pair sets that member, the order does not matter, and everything you do not mention is zeroed. This style is everywhere in professional firmware and in the Linux kernel, because it survives changes to the structure and documents itself.

Copying and Non-Constant Values

You can initialize a structure from another structure of the same type, and, in modern C, a local variable’s initializer can use ordinary variables:

int rate = 57600;
struct uart_cfg e = a;                                /* copy of a */
struct uart_cfg f = { "UART4", rate, 1, 0.5f };       /* runtime value */

Note that the constant-expression rule still applies to global and static structures, because their values must be known at compile time.

A Complete Example

Save the following as ep_struct_init.c. A small macro keeps the printing code short; the #v trick turns the variable name into text.

#include <stdio.h>

struct uart_cfg {
    char     port[8];
    unsigned baud;
    int      parity;
    float    timeout_s;
};

#define SHOW(v) printf("%-3s port=%-6s baud=%-6u parity=%d timeout=%.1f\n", \
                       #v, v.port, v.baud, v.parity, v.timeout_s)

int main(void)
{
    int rate = 57600;                                       /* runtime value */

    struct uart_cfg a = { "UART1", 115200, 0, 1.5f };       /* positional    */
    struct uart_cfg b = { "UART2" };                        /* rest become 0 */
    struct uart_cfg c = { .baud = 9600, .port = "UART3" };  /* designated    */
    struct uart_cfg d = { 0 };                              /* all zero      */
    struct uart_cfg e = a;                                  /* copy          */
    struct uart_cfg f = { "UART4", rate, 1, 0.5f };         /* non-constant  */

    SHOW(a);
    SHOW(b);
    SHOW(c);
    SHOW(d);
    SHOW(e);
    SHOW(f);
    return 0;
}

Build and Run

$ gcc -std=c11 -Wall -o ep_struct_init ep_struct_init.c
$ ./ep_struct_init

Expected Output

a   port=UART1  baud=115200 parity=0 timeout=1.5
b   port=UART2  baud=0      parity=0 timeout=0.0
c   port=UART3  baud=9600   parity=0 timeout=0.0
d   port=       baud=0      parity=0 timeout=0.0
e   port=UART1  baud=115200 parity=0 timeout=1.5
f   port=UART4  baud=57600  parity=1 timeout=0.5

Compare the rows against the code. Row b shows partial initialization, row c shows that naming members leaves the rest at zero, row d shows an empty port string because every byte is zero, and row e proves that a copy has the same values as the original. If you compile with -Wextra you may also see a warning about a missing initializer for rows b and c; the program is correct.

Why You Cannot Initialize Inside the Definition

A new learner often tries to set default values right inside the template:

struct bad {
    int x = 5;     /* not allowed in C */
};
error: expected ':', ',', ';', '}' or '__attribute__' before '=' token

The reason follows from Lecture 1: a definition reserves no memory, so there is nowhere to store a 5. Members are not variables until a variable of that structure exists. (This feature does exist in C++, which is a different language.) In C, the workaround is a ready-made constant, for example const struct uart_cfg default_uart = { "UART0", 9600, 0, 1.0f };, which you then copy: struct uart_cfg u = default_uart;.

Real-World Use Cases

  • Default configuration: keep one constant defaults structure in flash and copy it before changing a few fields.
  • Peripheral init: build a configuration with designated initializers and pass it to the driver.
  • Clearing state: start every local state structure as { 0 } so no stale stack data leaks into your logic.

Common Mistakes and Troubleshooting

MistakeWhat happensFix
Values in the wrong orderWrong data lands in wrong members, sometimes without any warningUse designated initializers
More values than membersCompiler warning or error: excess elementsCount members, or check for a changed definition
Assuming an uninitialized local is zeroRandom values, intermittent bugsAlways write an initializer such as { 0 }
Default values in the definitionSyntax errorUse a constant defaults structure
Too-long string for a char array memberWarning or truncated textSize the array for the text plus the terminating zero

Best Practices

  • Prefer designated initializers for anything with more than two members.
  • Never leave a local structure uninitialized.
  • Mark read-only default tables const so they can live in flash on a microcontroller.
  • Performance: initializing a large structure to zero costs a block fill, so avoid doing it repeatedly inside a time-critical loop when you can reuse the object.
  • Security: zero-initializing structures before filling them prevents leftover stack bytes, including padding, from leaking when you later transmit or log the data.

Summary and Key Takeaways

Remember

  • A brace list fills members in definition order; types must match.
  • Missing values mean zero, so { 0 } zeroes the whole structure.
  • .member = value designators are order-independent and safer.
  • Structures of the same type can be initialized or assigned from each other.
  • Default values cannot be written inside the definition in C.
  • Local structures may use runtime values; globals and statics need constants.

Conclusion

Initialization is where structures start to feel practical: one line can set up a whole peripheral configuration. With these techniques in hand, the next lecture of our free embedded C course shows how to read and change individual members with the dot operator, including strings and user input.

Frequently Asked Questions

How do I initialize a structure in C?

Use braces with values in member order, such as struct s v = { 1, 2 };, or use designated initializers like { .a = 1 }.

What happens to members I do not initialize?

When an initializer list is present, all remaining members are set to zero.

Are uninitialized structure members zero?

Only for global and static variables. Local variables without an initializer contain unpredictable values.

What are designated initializers?

A C99 feature that lets you write .member = value so you can initialize chosen members in any order.

Can I initialize a structure with variables instead of constants?

For local structures, yes, in C99 and later. Global and static structures need constant expressions.

Can I give default values inside the struct definition?

No, not in C. Create a constant structure with defaults and copy it.

How do I copy one structure to another?

Assign it directly: b = a; copies every member, as long as both have the same structure type.

Where is a free C programming course with embedded examples?

This free C programming course on EmbeddedPathashala explains every topic with tested embedded C examples.

Next in the Free Embedded C Course

Learn the dot operator, assigning strings to members, reading input into a structure and copying whole records.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →