{"id":81481,"date":"2021-07-07T09:00:46","date_gmt":"2021-07-07T03:30:46","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81481"},"modified":"2021-07-07T09:00:46","modified_gmt":"2021-07-07T03:30:46","slug":"union-in-c","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/","title":{"rendered":"Union in C"},"content":{"rendered":"<p>The C programming language has many features which may help programmers in easy coding. Unions are defined as a special data type. It is used to store a collection of different types of data. Unions are like structures. With the help of unions, you can use the same memory location for multiple purposes.<\/p>\n<h3>What are Unions in C?<\/h3>\n<p>Unions are like structures. It is used to store different types of data in the same memory location. The only difference between structures and unions is that unions only hold one value at a time whereas structures hold all their members. With the help of unions, you can define many members but only one of them can contain value at one time.<\/p>\n<h3>Defining union in C<\/h3>\n<p>As we know that unions can contain many members of different data types but it cannot handle all the members at the same time.<\/p>\n<p>The <strong>union<\/strong> keyword is used to define the unions.<\/p>\n<p><strong>Syntax:-<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">union UnionName{\n\/\/ member definitions;\n}\n<\/pre>\n<p><strong>Example of Union in C<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">union detail{\nint id;\nchar name[30];\nfloat salary;\n};\n<\/pre>\n<p>In the above, we have defined an union type named <strong>detail<\/strong> which has three members of different data types such as integer, character and float. Data type will occupy 30 bytes of memory space because character data type occupies 30 bytes of space and this is the maximum space which is occupied.<\/p>\n<h3>Creating union variables in C<\/h3>\n<p>Union is a user defined data type. To use and allocate memory for the union type, we first need to create variables.<\/p>\n<p><strong>Example of Creating union variables inside main() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">union detail{\nint id;\nchar name[30];\nfloat salary;\n};\nint main(){\nunion detail emp1,*emp2;\nreturn 0;\n}\n<\/pre>\n<p>In the above example, we created three union type variables. You can also create variables like below:-<\/p>\n<p><strong>Creating union variables outside the main() function<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">union detail{\nint id;\nchar name[30];\nfloat salary;\n}emp1, *emp2;\n<\/pre>\n<p>In both examples, we created union variables such as emp1 and a union pointer to emp2 to union type detail.<\/p>\n<p><strong>Example:- Basic example of union in C<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\nunion detail{\n   int bill;\n   char name[50];\n};\nint main( ) {\nunion detail a;   \t \nprintf(\"Total Memory size occupied by detail union type is: %d\\n\", sizeof(a));\nreturn 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Total Memory size occupied by detail union type is: 52<\/div>\n<h3>Accessing members of union in C<\/h3>\n<p>To access the members of union type, we use the . operator. And -&gt; is used to access pointer variables.<\/p>\n<p><strong>Example:- Accessing members of union in C<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include&lt;stdio.h&gt;\n#include&lt;string.h&gt;\nunion bestWebsite\n{\n   char name[20];\n   char tutorial[50];\n};\n \nvoid main( )\n{\nunion bestWebsite web;\nstrcpy( web.name, \"TechVidvan Tutorials!\");\nprintf(\"Best Website to learn C programming is: %s\\n\",web.name);\nstrcpy(web.tutorial, \"union in C!\");  \nprintf(\"Now you are doing: %s\\n\",web.tutorial);\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Best Website to learn C programming is: TechVidvan Tutorials!<br \/>\nNow you are doing: union in C!<\/div>\n<p>In the above example, we used web.name to access name for variable web and also used web.tutorial to access tutorial for variable web.<\/p>\n<h3>Difference between union and structure in C<\/h3>\n<p>The main difference between union and structure is that in structure, each variable has its own storage location but in union, all members use the size of its largest data member.<\/p>\n<p>There are a couple of differences between union and structure. Let\u2019s discuss below:-<\/p>\n<table>\n<tbody>\n<tr>\n<td><b>Distinctive Feature<\/b><\/td>\n<td><b>Structure<\/b><\/td>\n<td><b>Union<\/b><\/td>\n<\/tr>\n<tr>\n<td><b>Keyword<\/b><\/td>\n<td><span style=\"font-weight: 400\">It begins with the struct keyword.<\/span><\/td>\n<td><span style=\"font-weight: 400\">It begins with the union keyword.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Memory location<\/b><\/td>\n<td><span style=\"font-weight: 400\">In structure, all members of a structure have their own individual memory location for their storage.<\/span><\/td>\n<td><span style=\"font-weight: 400\">In union, all members of a union share the same memory location for their storage.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Initialization<\/b><\/td>\n<td><span style=\"font-weight: 400\">You can initialize many data members of a structure at one time.<\/span><\/td>\n<td><span style=\"font-weight: 400\">But union forbids the initialization of all its members.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Size<\/b><\/td>\n<td><span style=\"font-weight: 400\">Structure size depends on the sum of the individual sizes of its members.<\/span><\/td>\n<td><span style=\"font-weight: 400\">In union, total size is the largest size among its data members.<\/span><\/td>\n<\/tr>\n<tr>\n<td><b>Access<\/b><\/td>\n<td><span style=\"font-weight: 400\">All data members of the structure can be accessed at one time.\u00a0<\/span><\/td>\n<td><span style=\"font-weight: 400\">In union, you can access one data member at one time.<\/span><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Let\u2019s take a look at the below example:-<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\nunion detail\n{\n   char s1[32];\n   int id;\n}employee;\n\nstruct custom\n{\n   char s2[32];\n   int id_branch;\n}worker;\n\nint main()\n{\nprintf(\"TechVidvan Tutorials: Difference between union and structure!\\n\");\nprintf(\"Union size is: %d bytes\\n\", sizeof(employee));\nprintf(\"Structure size is: %d bytes\", sizeof(worker));\nreturn 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">TechVidvan Tutorials: Difference between union and structure!<br \/>\nUnion size is: 32 bytes<br \/>\nStructure size is: 36 bytes<\/div>\n<p>From the above example, we can see that:-<\/p>\n<ul>\n<li>The size of custom is 36 bytes because<\/li>\n<\/ul>\n<p>The size of s2[32] is 32 bytes.<br \/>\nSize of id_branch is 4 bytes.<\/p>\n<ul>\n<li>So, Total size of the custom is 36 bytes.<\/li>\n<\/ul>\n<p>But in union the size of detail is 32 bytes because the size of a union variable will always be the largest of its members.<\/p>\n<h3>Pointer to union in C<\/h3>\n<p>We can also use pointers to unions like structures. To access the members of unions, you have to use the arrow operator -&gt;.<\/p>\n<p><strong>Example:- pointer to unions<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\nunion point {\n  int a;\n  double c;\n};\nint main()\n{\n  union point point1;\n  point1.a = 10;\n  union point* point2 = &amp;point1;\n  printf(\"TechVidvan Tutorials: pointers to union!\\n\");\n  printf(\"%d\", point2-&gt;a);\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">TechVidvan Tutorials: pointers to union!<br \/>\n10<\/div>\n<h3>Use of Union in C<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;stdio.h&gt;\nunion student\n{\nint age;\nint total_marks;\n};\nint main()\n{\nprintf(\"TechVidvan TUtorial: Use of Unions in C!\\n\\n\");\nunion student s1;\ns1.age = 20;\ns1.total_marks = 754;\nprintf(\"Age of the student is: %d\\n\",s1.age);\nprintf(\"Total marks of the student is: %d\\n\",s1.total_marks);\nreturn 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">\n<p>TechVidvan TUtorial: Use of Unions in C!<\/p>\n<p>Age of the student is: 754<br \/>\nTotal marks of the student is: 754<\/p>\n<\/div>\n<p>From the above example, it is proved that you can only access one member at one time.<\/p>\n<h3>Advantages of Union in C<\/h3>\n<ul>\n<li>If you want to use same memory locations for two or more members, then you can use<br \/>\nunion.<\/li>\n<li>It occupies less memory than structure.<\/li>\n<\/ul>\n<h3>Disadvantages of Union in C<\/h3>\n<p>Only big disadvantage is that only last entered data can be stored in union.<\/p>\n<h3>Applications of C Union<\/h3>\n<ul>\n<li>With union, it is so easy to break up a STREAM of input.<\/li>\n<li>It is useful in situations where you want to use the same memory locations for two or more members.<\/li>\n<\/ul>\n<h3>Summary<\/h3>\n<p>Union is like structure. It is a user-defined data type. It is used to store different types of data in the same memory location.<\/p>\n<p>The main difference between union and structure is that in structure, each variable has its own storage location but in union, all members use the size of its largest data member.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The C programming language has many features which may help programmers in easy coding. Unions are defined as a special data type. It is used to store a collection of different types of data.&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81693,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3510],"tags":[3735,3736,3737,3738],"class_list":["post-81481","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c-programming","tag-adavantages-and-disadvantages-of-real-time-processing","tag-advantages-of-union-in-c","tag-disadvantages-of-union-in-c","tag-union-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Union in C - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn about union in C which is used to store different types of data in same memory location. Learn applications, advantages &amp; limitations.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/union-in-c\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Union in C - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn about union in C which is used to store different types of data in same memory location. Learn applications, advantages &amp; limitations.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/union-in-c\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-07T03:30:46+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Unions-in-C.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Union in C - TechVidvan","description":"Learn about union in C which is used to store different types of data in same memory location. Learn applications, advantages & limitations.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/","og_locale":"en_US","og_type":"article","og_title":"Union in C - TechVidvan","og_description":"Learn about union in C which is used to store different types of data in same memory location. Learn applications, advantages & limitations.","og_url":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-07T03:30:46+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Unions-in-C.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Union in C","datePublished":"2021-07-07T03:30:46+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/"},"wordCount":873,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Unions-in-C.jpg","keywords":["adavantages and disadvantages of real time processing","Advantages of Union in C","Disadvantages of Union in C","Union in C"],"articleSection":["C Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/union-in-c\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/","url":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/","name":"Union in C - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Unions-in-C.jpg","datePublished":"2021-07-07T03:30:46+00:00","description":"Learn about union in C which is used to store different types of data in same memory location. Learn applications, advantages & limitations.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/union-in-c\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Unions-in-C.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/Unions-in-C.jpg","width":1200,"height":628,"caption":"Union in C"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/union-in-c\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Union in C"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81481","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81481"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81481\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/81693"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81481"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81481"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81481"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}