Algebraic data type equivalent in C

I am writing a program that reads a stream of data and analyzes them for some values: integers, floats, characters, or a composite value that contains a set of values ​​(can be nested). How can I represent this in C? I was thinking about combining int , float , char , and then had an array of pointers to such joins for a composite value, but this cannot be nested.

+7
c types
source share
2 answers

(I imagine you are parsing an Xml file)

We will assume that you have a bunch of nodes. Each node can make a difference, it can be one of many relatives, and it can have children. This will give you a structure like:

  struct Node { DATA Value; DATATYPE Type; Node* nextSibling; Node* firstChild; }; 

DATA can be a union, as you described, or separate variables. However, since you will be reading values ​​from it in the same form as you saved them, the union should be in order. DATATYPE must be an enumeration.

+4
source share

Do you mean char , not char[] ? All char values ​​can be stored in int . In this case, it is safe that all int values ​​that you want (and all possible int values ​​on your computer) can be accurately represented by double .

So, I recommend a tree structure with double payloads in nodes. Use enum to distinguish between types, if necessary. You can represent the n-ary tree with one child pointer and one next pointer of a linked list ... Wikipedia has a diagram somewhere, but I cannot find it: v (.

+1
source share

All Articles