Welcome to our new forum
All users of the legacy CODESYS Forums, please create a new account at account.codesys.com. But make sure to use the same E-Mail address as in the old Forum. Then your posts will be matched. Close

explicit cast ENUM to UINT and vice versa

Anonymous
2017-11-15
2021-03-11
  • Anonymous - 2017-11-15

    Originally created by: P.C.

    Dear All,

    how do I cast explicitly ENUM to UINT (or other compatible type) and back UINT to ENUM?
    I haven't found dedicated conversion operators.
    I'd like to use 'strict' pragma and cast explicitely. Now I have to remove 'strict' and casting happens implicitly, which is bad of course...

    Thank you!

     
  • Anonymous - 2017-12-05

    Originally created by: scott_cunningham

    I don't know of an ENUM_TO_UINT() or UINT_TO_ENUM() type of conversion.

    BUT, you can turn on "Insert with namespace" in the SmartCoding options. This will include the namespace of the enum automatically, avoiding incorrect casting with another enum. At least it avoids issues when two enumerations have the same entry with different values.

    Then it's up to you to never do this:

    MyEnum := 53;
    

    And instead, do this:

    MyEnum := T_STATUS.IDLE_AFTER_FAULT;
    

    (Of course, you can include the namespace manually without turning on the SmartCoding feature...)

     
  • Lo5tNet - 2017-12-05

    Instead of converting could you just define the ENUM as type UINT instead?

    TYPE MyEnum :
    (
    Β  Β  Β EnumMember1 := 0,
    Β  Β  Β EnumMember2 := 1
    ) UINT;
    END_TYPE
    
     
  • laruso - 2021-03-11

    Here an explanation from the help files:

    β€žAs of CODESYS V3.5 SP7, each enumeration that you add to a project receives the 'strict' attribute automatically in the line above the TYPE declaration. For compiler versions >=3.5.7.0 , this causes compile errors in the following cases:
    - Arithmetic operation with variables of the enumeration type
    - Assignment of a constant value to a variable of the enumeration type, in which the constant does not correspond to an enumeration value
    - Assignment of a non-constant value to a variable of the enumeration type, in which the non-constant has another data type than the enumeration type

    Either you delete the {attribute 'strict'} from your ENUM and try again or you better follow the ideology of bulletproof programming, by checking your UINT against different values and then set the ENUM with one of it's members.

     

Log in to post a comment.