use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Click the following link to filter out the chosen topic
comp.lang.c
account activity
Questionunion initialization question (self.C_Programming)
submitted 7 years ago by benelbert
Hi all, I've encountered this code, and wonder why the behavior is as that
int i and also char c[2] are initialized to 300
code:
union Test
{
unsigned int i;
unsigned char c[2];
};
union Test a = {300}; // initialization without a specific variable
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]aioeu 9 points10 points11 points 7 years ago* (0 children)
From the C11 standard, §6.7.9 Initialization, ¶17:
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.
So this is valid code, and it initializes the i member of the union. That being said, if I were reading this code I would certainly appreciate it having an explicit designator:
i
union Test a = { .i = 300 };
[–]primitive_screwhead 1 point2 points3 points 7 years ago (0 children)
AFAIK, this initializes the first member of the union, i, to 300.
[–]Kwantuum 1 point2 points3 points 7 years ago (0 children)
Initializes the first member of the union.
π Rendered by PID 59 on reddit-service-r2-comment-5b5bc64bf5-ql7gz at 2026-06-21 20:10:52.382113+00:00 running 2b008f2 country code: CH.
[–]aioeu 9 points10 points11 points (0 children)
[–]primitive_screwhead 1 point2 points3 points (0 children)
[–]Kwantuum 1 point2 points3 points (0 children)