Structure Assignment in C- C Programming Course With Examples

🚀 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 · Structure and Union

Structure Assignment in C

Copy a whole record with one statement, understand the same-type rule, and see how structures behave when passed to and returned from functions.

What You Will Learn

  • How structure assignment in C copies every member in one statement
  • Why only variables of the same structure type can be assigned
  • Which operators structure variables do and do not support
  • How passing and returning structures by value works, with working code

Prerequisites

  • Defining and initialising structures (previous lectures of this chapter)
  • The dot operator and operator precedence
  • Basic printf and strcpy usage

Structure Assignment in C: The Big Idea

Structure assignment in C is the simplest way to duplicate a whole record with one statement. When two variables have the same structure type, writing b = a; copies every byte of a into b. No loop, no memcpy call, no member-by-member typing. If you have followed this free C programming course so far, you already know how to declare a structure and reach its members with the dot operator. Now we look at what happens when a structure is treated as one single value.

This matters a lot in embedded C programming. Sensor snapshots, protocol headers, configuration blocks and driver state are all structures. Being able to take a clean copy of one, hand a copy to a function, or return a copy from a function is a daily task. This lecture explains the rules, shows a complete program with output, and points out the traps that catch beginners.

The Rule: Same Type Only

Assignment between structure variables is legal only when both sides are of the same structure type. Two different struct declarations are two different types even if their members look identical. The compiler compares types, not shapes.

A Working Example

The program below declares a small struct reading, copies one variable into another, then changes the copy to prove the two are independent. Note the use of strcpy for the character array member: arrays cannot be assigned with = on their own, but they are copied happily as part of a whole-structure assignment.

#include <stdio.h>
#include <string.h>

struct reading {
    char  tag[8];
    int   id;
    float value;
};

int main(void)
{
    struct reading a = { "TEMP", 7, 36.5f };
    struct reading b;

    b = a;                    /* member-wise copy */
    strcpy(b.tag, "HUM");
    b.id = 8;
    ++b.value;                /* dot binds tighter than ++ */

    printf("a: %s %d %.1f\n", a.tag, a.id, a.value);
    printf("b: %s %d %.1f\n", b.tag, b.id, b.value);
    return 0;
}

Build and run it with a modern compiler:

gcc -std=c11 -Wall -Wextra -o a1 a1.c
./a1

Expected output:

a: TEMP 7 36.5
b: HUM 8 37.5

The original a is untouched. The copy b started as an exact duplicate, then diverged. Notice also ++b.value. The dot operator has higher precedence than the increment operator, so the compiler first picks the member b.value and then increments that member. You never need extra brackets for this.

What b = a Does in Memory
Before: a
TEMP736.5
Before: b
???
Copy: b = a (every byte of a goes into b)
TEMP736.5
After edits: b
HUM837.5

What Assignment Does Not Allow

A structure variable supports only a handful of operations. Understanding the list saves you from confusing compiler errors.

OperationAllowed?Notes
b = a; (same type)YesCopies every member, including embedded arrays
b = other_type_var;NoCompile error: incompatible types, even if members match
a == b, a != bNoCompare member by member instead
a + b, a < b, -a, ~aNoArithmetic, relational and bitwise operators do not accept structures
&a, sizeof aYesAddress and size work on any object
a.member with any operator valid for that memberYesa.value + 1.0f is a normal float expression

The compiler rejects mixed types. Here is a tiny program that tries it:

struct left  { int x; int y; };
struct right { int x; int y; };

int main(void)
{
    struct left  l = { 1, 2 };
    struct right r;
    r = l;
    return r.x;
}
gcc -std=c11 a3.c
a3.c: In function 'main':
a3.c:8:9: error: incompatible types when assigning to type 'struct right' from type 'struct left'
Do not reach for a cast. Casting a struct left to struct right is not allowed in C either. If you really need to convert between two layouts, write a small function that copies the members one by one. That also documents the conversion for the next engineer.

Passing and Returning Structures by Value

The same copy rule applies at function boundaries. Passing a structure as an argument copies it into the parameter. Returning a structure copies it out. The callee works on its own private copy, so changes inside the function never reach the caller’s variable.

#include <stdio.h>

struct reading {
    char  tag[8];
    int   id;
    float value;
};

struct reading bump(struct reading r)
{
    r.value += 1.0f;
    return r;
}

int main(void)
{
    struct reading orig = { "PRESS", 3, 100.0f };
    struct reading next = bump(orig);

    printf("orig.value = %.1f\n", orig.value);
    printf("next.value = %.1f\n", next.value);
    return 0;
}
gcc -std=c11 -Wall -Wextra -o a2 a2.c
./a2
orig.value = 100.0
next.value = 101.0

The function bump received a copy, added one to the copy, and returned the copy. The original stayed at 100.0. This is exactly how plain integers behave, and that consistency is the point: a structure is just a bigger value.

Cost of Copying on Small Microcontrollers

A copy is cheap for a 12-byte reading. It is not cheap for a 512-byte buffer descriptor on a Cortex-M0 running at a few megahertz, where each pass costs stack space and cycles. For large structures, pass a pointer (const struct reading *r) and use the arrow operator. You will practise this in later lectures on pointers to structures.

Pass by Value vs Pass by Pointer
By value
caller structcopy on stackcallee edits copy
By pointer
caller structaddress onlycallee edits original

Real-World Use Cases in Embedded Systems

  • Atomic-looking snapshots. Copy a shared status structure into a local variable once, then read the local copy without worrying about it changing under you. Remember that on a microcontroller the copy itself is not atomic, so briefly disable interrupts or use the platform’s lock around the copy if an interrupt handler writes the original.
  • Default configuration. Keep one constant structure with factory defaults and assign it to a working variable at start-up or on a reset command.
  • Undo and retry. Save a copy of a settings block before applying a change, so a failed update can restore the old state in one line.
  • Protocol frames. Build a header in a local structure, then assign it into the transmit queue slot.

Common Mistakes and Troubleshooting

MistakeWhat happensFix
Using == to compare two structuresCompile errorCompare each member, or write a small equal() helper
Assuming a pointer member is deep-copiedBoth copies point at the same memory; freeing one breaks the otherAllocate and copy the pointed-to data yourself
Assigning a string to a char array member with =Compile errorUse strcpy or, better, snprintf with the array size
Passing a huge structure by value in an interrupt handlerStack overflow on small devicesPass a pointer
Using memcmp on structures with paddingFalse mismatches because padding bytes are indeterminateCompare members individually (padding is the next lecture’s topic)

Best Practices

  • Prefer one-line assignment over hand-written member copying; it stays correct when you add a member later.
  • Use const parameters when you pass a pointer to a structure that the function must not change.
  • Initialise structures at the point of declaration so no member holds garbage.
  • Keep arrays and plain values inside the copied structure; avoid hidden pointer ownership unless you document it.

Structure Assignment vs memcpy

Beginners often ask whether they should write memcpy(&b, &a, sizeof a) instead of b = a. Both copy the same bytes, and a good compiler may even generate identical machine code. The difference is safety and clarity. Assignment is type-checked: the compiler refuses it when the types differ. memcpy accepts any two pointers, so a wrong size or a wrong variable compiles without a single warning and corrupts memory at run time.

Aspect<code>b = a;</code><code>memcpy(&amp;b, &amp;a, sizeof a);</code>
Type checkingYes, same type requiredNone, any pointers accepted
ReadabilityObvious intentNeeds a second look at the size argument
Works when types differNoYes, but dangerous
Needs a headerNoYes, <string.h>
Typical useCopying one structure to anotherCopying raw byte buffers

Step-by-Step: Safe Update with Rollback

Here is a pattern that shows why cheap structure copies are so useful in firmware. Suppose a device keeps its settings in one structure and a user command changes several fields. You want either all changes or none.

  1. Copy the live settings into a local variable: saved = live;
  2. Apply the new values to live, one member at a time.
  3. Validate the result. If any member is out of range, restore with live = saved;
  4. If everything is valid, keep the change and discard saved.

Without whole-structure assignment you would write one restore line per member, and each new setting would be one more line that someone must remember to add. With assignment, the rollback code never changes when the structure grows.

Key Takeaways

  • Assigning one structure variable to another of the same type copies all members, including array members.
  • Structures of different types cannot be assigned, even with identical members.
  • Structures support assignment, sizeof and address-of but not comparison or arithmetic.
  • Passing and returning by value copies the structure; use a const pointer for large ones.
  • The dot operator binds tighter than ++, so ++b.value increments the member.

Frequently Asked Questions

Can I assign one structure variable to another in C?

Yes, as long as both variables have the same structure type. The assignment copies every member, including array members, in a single statement.

Why does b = a work for a structure but not for an array?

The C language treats a structure as a single value, while an array name converts to a pointer in most expressions. Arrays inside a structure still get copied because the whole structure object is copied.

Can I compare two structures with ==?

No. C has no equality operator for structures. Compare the members one by one, or write a helper function.

Is structure assignment the same as memcpy?

The result is the same for the members, and compilers often generate a memcpy-style block copy. Assignment is type-checked and clearer, so prefer it when both sides have the same type.

Does assigning a structure copy the data a pointer member points to?

No. Only the pointer value is copied, so both structures end up pointing at the same memory. This is a shallow copy and you must handle ownership yourself.

Is passing a structure by value a good idea on a microcontroller?

It is fine for small structures. For large ones it wastes stack and time, so pass a const pointer instead.

Keep Learning C for Embedded Systems

This lecture is part of our free embedded C programming course. Practice every program on your own machine, then move on to the next lecture.

💬 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 →