C structures, unions, and enumerations for Java programmers

The C structure

The C struct is the precursor of the Java class. There are the following differences between the two.

See not much difference at all.

Structure example

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 ;

Structure operator

The dot operator

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.

Structures as variables

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.

Initialization of structures

struct state NC = { "North Carolina", {'N','C'}, 9222414 } ;

Unions

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 example

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.

Issues

Enumerated types

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 ;

typedef's

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 ;