ruk·si

🔹 C
Single-Member Structures

Updated at 2014-04-05 18:52

sizeof works even after passing a structure by reference, which is not true for all normal data types.

#include <stdio.h>
#include <stdint.h>

struct array_wrapper { uint8_t array[10]; };

void indirect_reference(struct array_wrapper * a)
{
    printf("%lu\n", sizeof(a->array));
}

int main()
{
    struct array_wrapper ar;
    indirect_reference(&ar); // => 10
    return 0;
}

Compile time error about trying to add two separate types.

#include <stdio.h>
#include <stdint.h>

// typedef uint32_t seconds_t;
// typedef uint32_t milliseconds_t;
struct seconds { uint32_t val; };
struct milliseconds { uint32_t val; };

struct seconds add_seconds(struct seconds a, struct seconds b)
{
    return (struct seconds) { a.val + b.val };
}

int main()
{
    struct seconds x = { 10 };
    struct milliseconds y = { 20 };
    struct seconds result = add_seconds(x, y); // error: incompatible type for
    printf("seconds: %u\n", result.val);
}

Sources