Home > Community > Forums > Functional Verification > How/Where/when to use unions

Email

* Required Fields

Recipients email * (separate multiple addresses with commas)

Your name *

Your email *

Message *

Contact Us

* Required Fields
First Name *

Last Name *

Email *

Company / Institution *

Comments: *

 How/Where/when to use unions 

Last post Mon, Nov 23 2009 12:10 PM by Vinayhonnavara. 1 replies.
Started by hipooja 23 Nov 2009 02:01 AM. Topic has 1 replies and 1159 views
Page 1 of 1 (2 items)
Sort Posts:
  • Mon, Nov 23 2009 2:01 AM

    • hipooja
    • Top 500 Contributor
    • Joined on Tue, Feb 24 2009
    • Ahmedabad, Gujarat
    • Posts 16
    • Points 345
    How/Where/when to use unions Reply

    I understand union to be a user defined data type that can store variables of different data types,however unlike class they do not contain methods to operate on the properties and they occupy the same memory as the largest data in them.

    I however do not know How ,when ,where and why to use unions as i have used classes extensively but not tried my hand at unions

    I wrote a simple code ,my idea was to display the properties of the union num ,defined below.i also want to know if unions and structs have a constructor like classes?

    program p1;
    typedef union packed {

    int i;
    real f;
    } num ;

    num n1 , n2;
    n1.f = 0.5;
    n2.i = -44;
    $display("f = %h\n",n1.f);
    endprogram

     

    I declareed the union to be packed as it otherwise issued an error that unpacked unions are unsupported,Secondly cant we define unions independently ,the way we define classes? I get a syntacx error at n1.f = 0.5 ,can you help me understand and use unions better?

     

    Regards,

    Pooja

    • Post Points: 20
  • Mon, Nov 23 2009 12:10 PM

    Re: How/Where/when to use unions Reply

    Hi Pooja,

    Basically you use unions to have different interpretations of a single daya type.

     

    Please check the following code, i have not used packed here and unpacked will work here. You missed the initial begin-end block. Other than that your code is flawless.

     program p1;
    typedef union packed {
    int i;
    real f;
    } num ;

    num n1 , n2;
    initial begin
    n1.f = 0.5;
    n2.i = -44;
    $display("f = %f\n",n1.f);
    end
    endprogram

    • Post Points: 5
Page 1 of 1 (2 items)
Sort Posts:
Started by hipooja at 23 Nov 2009 02:01 AM. Topic has 1 replies.