Hex Editor - Binary File Editing Software for Windows
Docs

Case Unions

A case union is a special construct offered by a Hex Editor Neo to dynamically select types at run time. It is virtually impossible to describe real-world data structures using only static types (types offered by C compiler, for example). And although dynamic types greatly increase the flexibility of the language to describe data structures, they still lack the ability to select one or another type based on run time conditions.

For example, imagine we have a byte in the data structure, followed by one of three different data structures, depending on this byte's value. Hex Editor Neo's case unions allow you to describe such data structure.

Case union syntax (copied from User-Defined Types section):

A union definition consists of zero or more of data fields:

case_union [name-id]
{
    case expression1:
        [ element_decl; … ]
    [
    case expression2:
        [ element_decl; … ]
    …
    ]
    [
    default:
        [ element_decl; … ]
    ]
};
element-decl:
  [ (field-decl | typedef-decl | const_decl | user-defined-type-decl) ; …]

field-decl:
  type var-decl [, var-decl …] ;
  
var-decl:
  (id | id[expression] | id:expression | id as type-id *)

Case union consists of one or more case blocks and an optional default block. Hex Editor Neo evaluates each expressionN and if it is nonzero, elements immediately following a case block are used. All other case blocks and default block are ignored. If none of case expressions is evaluated to a non-zero value, the default block is used. If the default block is omitted, a case union becomes an empty structure and is removed from the output.

struct B
{
    // …
};
   
struct C
{
    // …
};
   
struct A
{
    BYTE val;
    case_union
    {
        case val == 0:
            int a;
            int b;
        case val == 1:
            B b;
        default:
            C c;
    } s;
};

Case Union Optimization

All case expressions are evaluated at compile time. If an expression is a non-zero constant expression, a whole case union becomes equivalent to a corresponding structure. If all case expressions evaluate to constant zero, the whole case union becomes equivalent to a structure with fields from the default block. If there is no default block in a case union, it becomes an empty structure and is eliminated from the output.