Sum data type: Difference between revisions

Added C implementation
(Added C implementation)
Line 34:
, ( VOID ): print( ( "empty", newline ) )
ESAC</lang>
 
=={{header|C}}==
C has the union data type which can store multiple variables at the same memory location. This was a very handy feature when memory was a scarce commodity. Even now this is an essential feature which enables low level access such as hardware I/O access, word or bitfield sharing thus making C especially suited for Systems Programming.
 
What follows are two example programs. In both an union stores an integer, a floating point and a character at the same location. If all values are initialized at once, data is corrupted, as shown in the first example. Proper use of unions require storing and retrieving data only when required.
 
==={{header|Incorrect usage}}===
<lang C>
#include<stdio.h>
 
typedef union data{
int i;
float f;
char c;
}united;
 
int main()
{
united udat;
 
udat.i = 5;
udat.f = 3.14159;
udat.c = 'C';
 
printf("Integer i = %d , address of i = %p\n",udat.i,&udat.i);
printf("Float f = %f , address of f = %p\n",udat.f,&udat.f);
printf("Character c = %c , address of c = %p\n",udat.c,&udat.c);
 
return 0;
}
</lang>
'''Output :'''
<pre>
Integer i = 1078529859 , address of i = 0x7ffc475e3c64
Float f = 3.141557 , address of f = 0x7ffc475e3c64
Character c = C , address of c = 0x7ffc475e3c64
</pre>
 
==={{header|Correct usage}}===
<lang C>
#include<stdio.h>
 
typedef union data{
int i;
float f;
char c;
}united;
 
int main()
{
united udat;
 
udat.i = 5;
 
printf("Integer i = %d , address of i = %p\n",udat.i,&udat.i);
 
udat.f = 3.14159;
 
printf("Float f = %f , address of f = %p\n",udat.f,&udat.f);
 
udat.c = 'C';
 
printf("Character c = %c , address of c = %p\n",udat.c,&udat.c);
 
return 0;
}
</lang>
'''Output:'''
<pre>
Integer i = 5 , address of i = 0x7ffd71122354
Float f = 3.14159 , address of f = 0x7ffd71122354
Character c = C , address of c = 0x7ffd71122354
</pre>
 
=={{header|Factor}}==
503

edits