A keyword in various programming languages whose syntax is similar to or derived from C (C++, C#, Swift, Go, Rust, etc.). Use a specific programming language tag to tag questions involving use of a `struct` as syntax and semantics can be language dependent. Keyword defines or declares a data type composed of other data types. Each member of a struct has its own area of memory (as opposed to a `union` whose members share a single area of memory).
A struct
consists of a sequence of field names and their types (struct
members), for example:
struct s {
int *i; // pointer to an int
char *s; // pointer to a char
double d; // a double
int (*pFunc)(char *, int); // pointer to a function
};
A struct
can also contain bit fields to allow bit-level memory addressing:
struct bits {
unsigned int b1 : 1;
unsigned int b2 : 1;
unsigned int b3 : 1;
unsigned int b4 : 1;
unsigned int b5 : 1;
unsigned int b6 : 1;
unsigned int b7 : 1;
unsigned int b8 : 1;
};
Each member of a struct
has its own area of memory as opposed to a union
in which the members share the same area of memory.
The syntax for defining/declaring a struct
as well as what it is possible to include in a struct
definition/declaration varies between the various C style languages that use the keyword (e.g. member functions not allowed in C but are in C++ though both allow a pointer to a function).
The syntax for specifying and using a struct
to define/declare variables may vary slightly between various C style programming languages ( s myVar;
versus struct s myVar;
)
Dynamic languages generally use some form of associative array in place of struct
s. The Pascal family of languages refer to these date types as record
s.