Thread: Is it possible to typecast enum variable in C

  1. #1
    Registered User
    Join Date
    Feb 2014

    Is it possible to typecast enum variable in C

    It seems the enum constants are signed int as per C standard, please correct me if it is different.

    Is there anyway to define an enum and typecast to other type say "unsigned int"?

    In the following pseudo code, the enum variable "file1.status" was assigned with the return value of function "get_value", which is of type unsigned int.

    typedef enum {
        OPEN    = 0,
        CLOSE    = 1,
        SUCCESS    = 3,
        FAILURE    = 4
    } t_status;
    struct file_status {
        t_status status;
    } file1;
    unsigned int get_value()
        unsigned int value;
        return value;
    void main()
        file1.status = get_value();

    I am getting Implicit conversion warning(unsigned int to signed int). Is it possible to fix this warning by typecasting the enum as unsigned int.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    So why can't get_value() return the enumeration type itself?

    Which begs the question, how are you ensuring that the unsigned value you are returning is actually a member of your enumeration?

    A possible hack is to introduce an enum constant which cannot be represented as an int, eg
    This (for me with gcc) makes the underlying enum integer type unsigned.
    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.

  3. #3
    Registered User
    Join Date
    Feb 2014
    I don't have control on the get_value(). It is a generic function which returns the value of bits at the given bit positions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Tic Tac Toe with enum. Assigning a char to an enum value.
    By Iceboxes in forum C++ Programming
    Replies: 6
    Last Post: 11-30-2013, 09:58 AM
  2. variable of type enum to be entered by user
    By Clayg in forum C Programming
    Replies: 4
    Last Post: 12-07-2011, 08:22 AM
  3. how to declare an external variable of type "enum"?
    By Adam Rinkleff in forum C Programming
    Replies: 28
    Last Post: 06-23-2011, 09:52 PM
  4. Convert enum member variable to string?
    By Programmer_P in forum C++ Programming
    Replies: 13
    Last Post: 05-10-2010, 02:59 PM
  5. typecast overloading
    By Trauts in forum C++ Programming
    Replies: 2
    Last Post: 05-14-2003, 04:44 PM

Tags for this Thread