Skip to content

Unions #188

Open
Open
Unions#188
@sblionel

Description

@sblionel

For many years, I have heard complaints from users at the lack of unions in Fortran. DEC added unions as part of its STRUCTURE/RECORD extension in 1985, but J3/WG5 never seriously considered adding unions as far as I know. Some considered unions like EQUIVALENCE, a bad programming practice. In an ideal world, I would agree, but there are just too many places where non-Fortran APIs use unions (Windows API for one) and the lack of a way to represent these in Fortran is considered a defect.

Given that a common use of unions is in C-friendly APIs, I want to propose unions in the context of C interoperability. Here is my idea:

  • Support the DEC UNION/MAP syntax for interoperable types only
  • Disallow types with an "ultimate component" of a union from: formatted I/O without DT, default initialization, structure constructors (only those that don't give names for all their components?). Am I missing anything? I thought about intrinsic assignment, but I think this is OK since an interoperable type can't contain a pointer, allocatable or coarray component. Basically, the things that imply a component order would be excluded.

Many compilers already support the DEC syntax, so this would be relatively easy to implement.

As a reminder, it would look something like this:

type, bind(C) :: union_type
  union
    map 
      integer : I
    end map
    map
      real :: R
    end map
  end union
end type union_type
type(union_type) :: UR

One could then reference UR%I or UR%R which would share the same memory location. The DEC syntax didn't allow naming unions or maps - I am not sure there is a benefit in doing so.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Clause 7Standard Clause 7: TypesFortran 202yProposals targeting the standard after F2023unsubmittedHas not been submitted to the committee yet

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions