C does not allow you to declare class types (as you
can in Java using the class
construct), but you can declare
C structures using the struct
construct. A C
structure is like a Java class that only contains public
data members — there must be no functions, and all parts
are visible to any code that knows the declaration. For
example:
struct point { int x, y; };
This declares a type called struct point
(NB:
‘struct
’ is part of the
name; point
is known as the
structure type's tag).
Members of a C structure are accessed using the
.
operator, as class members
can be in Java:
struct point location; location.x = 10; location.y = 13;
A structure object may be initialised where it is defined:
struct point location = { 10, 13 }; /* okay; initialisation (part of definition) */ location = { 4, 5 }; /* illegal; assignment (not part of definition) */
In C99, you can create anonymous structure objects to perform compound assignement:
location = (struct point) { 4, 5 }; /* legal in C99 */
In C99, a structure initialisation can specify which members are being set:
struct point location = { .y = 13, .x = 10 }; /* legal in C99 */
Unlike Java, where class variables are references to objects, C structure variables are the objects themselves. Assigning one to another causes copying of the members:
struct point a = { 1, 2 }; struct point b; b = a; /* copiesa.x
tob.x
, anda.y
tob.y
*/ b.x = 10; /* does not affecta.x
*/