Lecture 8
Lecture 8
Lectures 8
Masamba Benson
[email protected]
Lecture 8: Outline
• Structures [Kochan, chap 9]
– Defining and using Structures
– Functions and Structures
– Initializing Structures. Compound Literals
– Arrays of Structures
– Structures Containing Structures and/or Arrays
• More on Data Types [Kochan, chap 14]
– Enumerated Data Types
– The typedef Statement
– Data Type Conversions
The concept of structures
• Structure: a tool for grouping heterogenous elements together.
• Array: a tool for grouping homogenous elements together
• Example: storing calendar dates (day, month, year)
• Version1: using independent variables:
• int month = 9, day = 25, year = 2004;
• Using this method, you must keep track of three separate variables
for each date that you use in the program—variables that are
logically related. It would be much better if you could somehow
group these sets of three variables together. This is what the
structure in C allows you to do !
Example: structures
struct date Defines type struct date, with 3 fields of type int
{ The names of the fields are local in the context
int month; of the structure.
int day; A struct declaration defines a type: if not followed by a
int year; list of variables it reserves no storage; it merely
}; describes a template or shape of a structure.
if ( today.day != daysPerMonth[today.month - 1] ) {
tomorrow.day = today.day + 1;
tomorrow.month = today.month;
tomorrow.year = today.year;
}
else if ( today.month == 12 ) { // end of year
tomorrow.day = 1;
tomorrow.month = 1;
tomorrow.year = today.year + 1;
}
else { // end of month
tomorrow.day = 1;
tomorrow.month = today.month + 1;
tomorrow.year = today.year;
}
printf ("Tomorrow's date is %i/%i/%i.\n", tomorrow.month,
tomorrow.day, tomorrow.year );
return 0;
}
Operations on structures
• Legal operations on a structure are :
– copying it or assigning to it as a unit
• this includes passing arguments to functions and returning values
from functions as well.
– taking its address with &
– accessing its members.
– structures may not be compared as units !
– a structure may be initialized by a list of constant member values
Example: determine tomorrow’s
date (Version 2)
// Program to determine tomorrow's date
#include <stdio.h>
#include <stdbool.h>
struct date
Defines type struct date as a global type
{
int month;
int day;
int year;
}; Declares a function that takes a
struct date as a parameter
int numberOfDays (struct date d);
. . .
event.sdate.month = 10;
Structures containing arrays
struct month
{
int numberOfDays;
char name[3];
};
. . .
aMonth.numberOfDays = 31;
aMonth.name[0] = 'J';
aMonth.name[1] = 'a';
aMonth.name[2] = 'n';
Enumerated data type
• You can use the enumerated type to declare symbolic names to represent
integer constants.
• By using the enum keyword, you can create a new "type" and specify the
values it may have.
• Actually, enum constants are type int; therefore, they can be used wherever
you would use an int.
• The purpose of enumerated types is to enhance the readability of a
program.
• enum primaryColor { red, yellow, blue };
• enum primaryColor myColor, gregsColor;
• myColor = red;
• if ( gregsColor == yellow ) …
Enumerated data type
• The C compiler actually treats enumeration identifiers as integer constants.
Beginning with the first name in the list, the compiler assigns sequential
integer values to these names, starting with 0.
• enum month thisMonth;
• ...
• thisMonth = february;
• the value 1 is assigned to thisMonth because it is the second identifier
listed inside the enumeration list.
• If you want to have a specific integer value associated with an enumeration
identifier, the integer can be assigned to the identifier when the data type is
defined. Enumeration identifiers that subsequently appear in the list are
assigned sequential integer values beginning with the specified integer
value plus 1. For example, in the definition
• enum direction { up, down, left = 10, right };
• an enumerated data type direction is defined with the values up, down, left,
and right. The compiler assigns the value 0 to up because it appears first in
the list; 1 to down because it appears next; 10 to left because it is explicitly
assigned this value; and 11 to right because it appears immediately after left
in the list.
Example: enum
// Program to print the number of days in a month
#include <stdio.h>
int main (void)
{
enum month { january = 1, february, march, april, may,
june,july, august, september, october, november, december
};
enum month aMonth;
int days;
printf (“Enter month number: “);
scanf (“%i”, &aMonth);
Cont.
switch (aMonth ) {
case january: case march: case may: case july:
case august: case october: case december:
days = 31; break;
case april: case june: case september: case november:
days = 30; break;
case february:
days = 28; break;
default:
printf (“bad month number\n”);
days = 0; break;
}
if ( days != 0 )
printf (“Number of days is %i\n”, days);
if ( amonth == february )
printf (“...or 29 if it’s a leap year\n”);
return 0;
}
The typedef statement
• C provides a capability that enables you to assign an alternate
name to a data type. This is done with a statement known as
typedef.
• The statement
typedef int Counter;
• defines the name Counter to be equivalent to the C data type int.
Variables can subsequently be declared to be of type Counter, as
in the following statement:
Counter j, n;
• The C compiler actually treats the declaration of the variables j and
n, shown in the preceding code, as normal integer variables.
• The main advantage of the use of the typedef in this case is in the
added readability that it lends to the definition of the variables.
• the typedef statement does not actually define a new type—
only a new type name.
The typedef statement
• In forming a typedef definition, proceed as though a normal variable
declaration were being made. Then, place the new type name where the
variable name would normally appear. Finally, in front of everything, place
the keyword typedef:
• typedef char Linebuf [81];
• defines a type called Linebuf, which is an array of 81 characters.
Subsequently declaring variables to be of type Linebuf, as in
• Linebuf text, inputLine;
typedef struct
{
int month;
int day;
int year;
} Date;
Date birthdays[100];
Data type conversions
• Expressions: Operands and operators
• Operands may be of different types; issue: how is the expression
evaluated and what is the type of the result ?
• Example: the case examined in lecture 2 was with the data types
float and int: an operation that involved a float and an int was
carried out as a floating-point operation, the integer data item
being automatically converted to floating point.
• N=8
• W= 11111011
• W=(-1)*27+1*26+1*25+1*24+1*23+0+1*21+1*20 =-5
Two’s complement example
• A convenient way to convert a negative number from
decimal to binary:
1. add 1 to the value
2. express the absolute value of the result in binary
3. and then ―complement‖ all the bits; that is, change all 1s to 0s
and 0s to 1s.
• Example: convert -5 to binary:
1. First 1 is added, which gives -4;
2. Value 4 expressed in binary is 00000100
3. Complementing the bits produces 11111011.
Signed & Unsigned types
• If in an expression appear both signed and unsigned operands, signed
operands are automatically converted to unsigned
• Converting signed to unsigned:
– No change in bit representation
– Nonnegative values unchanged
– Negative values change into positive values !
– Example: int x=-5; unsigned int ux=(unsigned int) x;
printf(“%ud \n”,ux); // 4294966*62
• Conversion surprises:
int a=-5;
unsigned int b=1;