Constants
public static final . . .
#define MAX 20 /* C implementation */ /* uses preprocessor macro to replace */ /* MAX with 20 everywhere in the code */
const
for declarations
const int MAX = 20; const double PI = 3.141592;
Arrays
Declaration syntax:
type identifier [# elements];
Example declarations:
(no initialization of elements)
int counts[100]; double temps[12];
Declaration with initialization:
char msg1[] = "Wow!";
double values[] = {1.3, -6.2, 100.95};
int sums[500] = {0};
Using arrays:
int Ar[12];
for (i = 0; i < 12; i++) {
Ar[i] = i;
}
4 items you need to know about arrays:
1. array size is static
(it is a fixed-size, once it is declared)
2. no equivalent to the Java length
If you really need it,
you might try using the sizeof operator.
sizeof returns the size in bytes
ArLength = (sizeof Ar) / (sizeof Ar[0]);
3. cannot assign to an array
int X[2] = {0, 1};
int Y[2];
Y = X; // NOT ALLOWED
4. NO bounds checking!
int flowers[4]; flowers[4] = 100; // OK flowers[20] = -1; // OK
This code:
C-style Strings
'\0'
(the NULL character)
char msg2[] = "YES"; -------------------------- | 'Y' | 'E' | 'S' | '\0' | -------------------------- char msg3[5] = "NO"; ---------------------------------- | 'N' | 'O' | '\0' | '\0' | '\0' | ----------------------------------
Enumerations
enum identifier {id1, id2 . . .};
Enumeration example:
enum color {red, orange, yellow, green, blue};
color swatch; // declaration
swatch = green; // valid assignment
swatch++; // NOT ALLOWED
swatch = red + orange; // NOT ALLOWED
More examples:
enum wierd {A, B=12, C, D};
enum sames {zero, naught=0, one, uno=1};
More on assignment:
(assignment allowed, if in range)
enum fingers {thumb=1, pinky=5};
fingers pointer; // declaration
pointer = fingers (2); //type cast
Be careful!
The largest value in range is
defined as one less than
the power of 2 larger
than largest enum value
So, for this example
8 - 1 = 7
Structures
Declaration example:
struct animal {
char name[20];
bool endangered;
int population;
}
Use Example:
animal cat2; // declaration cat2.name = "shorthair"; cat2.endangered = false; cat2.population = 3000000;
Further use example:
animal dog1 = {"labrador", false, 250000};
//looks like an array initialization
animal lab;
lab = dog1; // memberwise assignment
Structures and Arrays together
struct point {
int x;
int y;
};
point set[3] = {
{0, 0}, // set[0]
{1, 2} // set[1]
};
set[2].x = 3;
set[2].y = 4;
Needed, but deferred discussion:
Using structures and arrays together with pointers.
Unions
Declaration example:
union mostlyuseless {
int int_value;
double double_value;
};
We get 1 piece of memory space,
large enough to hold either the int or the
double.
Use example:
mostlyuseless X; // declaration X.int_value = 20; // X holds an int X.double_value = 6.33; // now X is a double
Programming issue: which type is it now?