Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to use anonymous union within struct in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
 
typedef struct TEST {
    bool b;
    union  {
        long n;
        char s[12];
        float f;
    };
} TEST;
 
int main() {
    TEST t;
     
    printf("size: %d\n\n", sizeof(t));
      
 
    t.b = true;
 
    t.n = 8493;
    printf("(set)t.b:%s\n", t.b ? "true" : "false");
    printf("(set)t.n: %d\n", t.n);
    printf("t.s: %s\n", t.s);
    printf("t.f: %f\n", t.f);
    printf("size: %d\n\n", sizeof(t));
 
    strcpy(t.s, "c union");
    printf("(set)t.b:%s\n", t.b ? "true" : "false");
    printf("t.n: %d\n", t.n);
    printf("(set)t.s: %s\n", t.s);
    printf("t.f: %f\n", t.f);
    printf("size: %d\n\n", sizeof(t));
      
    t.f = 3.14;
    printf("(set)t.b:%s\n", t.b ? "true" : "false");
    printf("t.n: %d\n", t.n);
    printf("t.s: %s\n", t.s);
    printf("(set)t.f: %f\n", t.f);
    printf("size: %d\n\n", sizeof(t));
     
    return 0;
}
  
 
  
  
/*
run:
  
size: 24

(set)t.b:true
(set)t.n: 8493
t.s: -!
t.f: 0.000000
size: 24

(set)t.b:true
t.n: 1853169763
(set)t.s: c union
t.f: 18965745136684753516509528064.000000
size: 24

(set)t.b:true
t.n: 1078523331
t.s: ��H@ion
(set)t.f: 3.140000
size: 24
  
*/

 



answered Dec 27, 2020 by avibootz
edited Dec 28, 2020 by avibootz

Related questions

1 answer 175 views
2 answers 272 views
1 answer 158 views
158 views asked Mar 17, 2018 by avibootz
1 answer 68 views
68 views asked Nov 22, 2024 by avibootz
1 answer 134 views
134 views asked Mar 17, 2018 by avibootz
1 answer 136 views
136 views asked Mar 17, 2018 by avibootz
1 answer 118 views
...