Union Data Types | C Programming Tutorial

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

You have simplified everything for I now know the difference between Unions and Structures in C

ebrimagajaga
Автор

Excellent explanation! But perhaps there should be some mention of the concept of "most significant bytes" vs "least significant bytes". Some new learners may be surprised by the output, when they think that assigning one value will completely overwrite the previous value - which may not occur if the previous value is larger than the subsequent value. Such as in this example whereby the char type is assigned 127, but 'int a' is suddenly 383 instead of 127.

#include <stdio.h>

typedef union MyUnion
{
int a;
char b;
}myUnion;

int main(void)
{
myUnion abc;

abc.a = 256;
printf("%d %d\n", abc.a, abc.b); // 256 0

abc.b = 127;
printf("%d %d\n", abc.a, abc.b); // 383 127

return 0;
}

Binary 256: 0000 0001 0000 0000
Binary 127: 0111 1111. <- 'char' overwriting the least significant bytes
Binary 383: 0000 0001 0111 1111

GaryChike
Автор

Great lesson, as always (even if I'm late to the party)!

It might be difficult for new programmers to come up with use cases where unions are useful "for real". I'd no idea myself before a senior programmer showed me how he utilized unions for parsing protocols of various kind. It blew my mind :)

jakobfredriksson
Автор

Hi sir good to see you back
Can you explain what are anonymous unions and structs and why is it called anonymous...
Thank you for understanding...

ramakrishna
Автор

What about these anonymous unions, are they special or just like any other nested union ?

justcurious
Автор

6:43 why is that 48 bytes? We have a 32 characters array, a double and an int, 32 bytes + 8 bytes + 4 bytes = 44 bytes and we have a sizeof(mydata2) is 48 bytes. WHY?

hanaksi
Автор

const struct {uint32_t len; const char *data;} control_blocks[ ] = {
{count_of(word0) - 1, word0}, // Skip null terminator
{count_of(word1) - 1, word1},
{count_of(word2) - 1, word2},
{count_of(word3) - 1, word3},
{count_of(word4) - 1, word4},
{count_of(word5) - 1, word5},
{0, NULL} // Null trigger to end chain.
};
Sir How this struct Works that's i got from pi pico data sheet basically i am doing embedded developing kindly help me with this ....

salmantechnologies
Автор

why dodge talking about talking about polymorphism?

DemoboyOot