The C struct
is the precursor of the Java class
.
There are the following differences between the two.
struct
rather than class
.struct
is very, very rarely put in its own file.struct
definitions end with a semi-colon.struct
definitions don't have all those
public
, private
, static
,
etc. modifiers.struct
definitions don't have methods.See not much difference at all.
struct state { char *Name ; char Abbrev[2] ; int Population ; } struct state NC ; NC.Name = "North Carolina" ; NC.Abbrev[0] = 'N' ; NC.Abbrev[1] = 'C' ; NC.Population = 9222414 ;
The dot operator joins a structure variable with a
field or member name, just like in Java.
The .
operator has the highest binary operator
precedence level and has left-to-right precedence.
In ANSI C, one structure can be assigned (with =
) to another
and structures can be passed to and returned from functions.
This involves copying the entire structure and is reasonable only with
very small structures.
In Java, assigning class objects only involves copying a pointer.
struct state NC = { "North Carolina", {'N','C'}, 9222414 } ;
The union
is a structure in which only
one field can be active. The syntax for accessing union
fields is identical to the syntax for accessing structure fields.
Unions are confusing. Java wisely avoids them.
union Term { char variable[13] ; double constant ; } union Term t1, t2 ; strcpy(t1.variable, "CSCI255") ; t2.constant = 255.0 ;
Telling the variable
and constant
apart is not in the union
's job description.
union
structure
Enumerated types are a great way to assign logical numbers
to useful integers.
They look better those DEFINE
's in the
ICMP include file.
Java did not have enumerations until version 1.5, when they were announced with great bravado.
enum ResistorCode {black, brown, red, orange, yellow, green, blue, violet, grey, white } ; enum ResistorCode band1, band2, band3 ; band1 = orange ; band2 = orange ; band3 = brown ;
The typedef
is C's succinct way of defining new types.
It is sometimes used in a confusing ways with similarly named
identifiers. Be careful.
typedef struct state State ; State NC ;