Thread: Beginner Curiosity

  1. #1
    Registered User
    Join Date
    Jul 2016
    Posts
    9

    Beginner Curiosity

    Hello, everyone. I recently started learning C language and I was trying to figure out how unions work. I wanted to try something with it but I can't quite understand the result. For all I know, unions can be used to convert data types since they are using the same memory address but I'm not good with variable types so can someone explain why the code's doing this? What's the relation between "1101004800" and "20,423" ? Why do I get a "0,00000" when I try to display int value as float? What is the effective way to convert these types (double, int, float etc.) with or without using unions? Here's the code and the result. Thank you for your answers.
    Code:
    #include <stdio.h>
    #include <string.h>
    typedef union {
        float fvar;
        int ivar;
    }obj;
    main(){    
    obj a;
    a.ivar=20;
    printf("%f\n",a.fvar);
    a.fvar=20,423;
    printf("%d\n",a.ivar);
    }


    Code:
    0.000000
    1101004800
    If you have other examples in which useful ways of how to use unions are shown, I'd be grateful to see them as well. Have a good day.

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    For all I know, unions can be used to convert data types since they are using the same memory address but I'm not good with variable types so can someone explain why the code's doing this?
    O_o

    You have the same fundamental misunderstanding of `union` both in practice and according to the standard shared by a lot of people relatively new to the language.

    The `union`, as you've used here, is not converting one type to another type.

    The `union`, again as you've used here, is attempting to use the representation of a value of one type as the representation of a value of a different type.

    You may think I'm being unnecessarily pedantic, but the distinction between what you seem to be calling data conversion and conversion reusing representation is very important.

    I don't have the time for a complete explanation, but the general issue is found in how floating point variables are stored by a computer versus how integer values are stored by a computer.

    By the by, writing one member of a `union` then reading a different member of the same `union` is basically illegal.

    What is the effective way to convert these types (double, int, float etc.) with or without using unions?
    What, exactly, do you mean by "convert" here? You should give an example of what you expect.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  3. #3
    Registered User
    Join Date
    Jul 2016
    Posts
    9
    Quote Originally Posted by phantomotap View Post
    O_o

    What, exactly, do you mean by "convert" here? You should give an example of what you expect.

    Soma
    I'm just trying to understand where and why we need unions. The only thing I could find about them is that they can help me handle a data type that I don't know but I can't understand why we would possibly need them.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,422
    Unions were introduced into C way back in the early 1970's, as a way of efficiently storing mutually exclusive data sets on machines with very little memory.

    This is at a time when memory cost something like $1 per byte (Memory Prices 1957 to 2015 - 1973,12K,$4680.00), so there was always a need to make every last bit count.

    Typically, you would have something like
    Code:
    struct record {
      int type;
      union {
        int a;
        char b;
        float c;
      } var;
    };
    So:
    if .type was 1, you would read and write var.a
    if .type was 2, you would read and write var.b
    if .type was 3, you would read and write var.c
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    I can't understand why we would possibly need them.
    O_o

    The post by Salem answers your questions, but I wanted to add a bit of context to "where".

    If my grepping is correct, I've used `union` only four separate places in my library code which is now rather large and has been in development for more than a decade. You'd find only two legitimate uses of `union` in the thing. The other two uses are a hack to fix an error in a compiler I doubt anyone still uses and a performance hack that isn't enabled by default because of how rarely compilation results in a correct binary executable.

    In other words, you can probably consider `union` a rare need.

    If you understand the post Salem wrote, I'd suggest you continue with your education for now even if you don't quite appreciate the "where" of `union` for now.

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  6. #6
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466
    Quote Originally Posted by phantomotap View Post
    O_o
    By the by, writing one member of a `union` then reading a different member of the same `union` is basically illegal.
    Soma
    From what I understand of the C standard, this is correct. From what I understand of modern programming languages, the use of union is basically obsolete. No modern language that I know of provides it, as it does not provide a useful "use case". I'm sure there is some clever and efficient trickery that can be done with it, but as the OP has discovered, the semantics are not well-defined, at least in a clear way..

    I thought a union was basically an efficiency hack where the same memory space could be used to store a single value of different type. For example, you could store a 32 bit int OR a 32 bit float in the same memory space, and refer to both by the same identifier. But you cannot use it to convert an int to a float, or vice-versa, because of that fact that the bit-level representation of ints and floats is entirely different.
    Last edited by MacNilly; 07-16-2016 at 04:07 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin.get() curiosity
    By lilrayray in forum C++ Programming
    Replies: 3
    Last Post: 09-03-2006, 10:07 PM
  2. out of curiosity...
    By YankeePride13 in forum A Brief History of Cprogramming.com
    Replies: 8
    Last Post: 01-28-2006, 10:04 AM
  3. Out of curiosity?
    By voodoo3182 in forum Tech Board
    Replies: 6
    Last Post: 08-05-2005, 10:10 AM
  4. Out of curiosity...
    By gcn_zelda in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 01-09-2005, 12:53 PM
  5. Just out of curiosity
    By mithrandir in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 09-10-2001, 12:44 PM

Tags for this Thread