Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

Module 1

C Programming Summary

Dr. Hau Yuan Wen (Jasmine)


School of Biomedical Engineering and Health Sciences

www.utm.my innovative ● entrepreneurial ● global 1


Software Development Process for
Embedded System

www.utm.my innovative ● entrepreneurial ● global 22


Embedded Programming
Small, Efficient, Reliable, Reusable Code

www.utm.my innovative ● entrepreneurial ● global 33


Brief Review of
Embedded C Programming

www.utm.my innovative ● entrepreneurial ● global 44


main()
 Every C language program MUST have AT LEAST ONE
function, namely main().
 Starting point when the program code is executed.
 Considered as the lowest-level task.
void main() void main()
{ { //< statements>
// < statements> while (1)
} {
// < statements>
Every embedded microcontroller application has
}
an infinite loop built into it somewhere, such as
}
the while(1), to prevent the program from
running out of things to do and doing random
things that may be undesirable.

www.utm.my innovative ● entrepreneurial ● global 55


C Basic syntax
; To indicate the end of an expression.
{}  To delineate the beginning and the end of the function’s
contents.
 To indicate when a series of statements is to be treated as a
single block
“text” To mark the beginning and the end of a text string.
// Single-line comments
/* */ Multi-line comments
# Preprocessor instruction
#include<..>: To include the content of other system header files
#include “..“: To include the content of other user header files
#define: To define constant and macro

www.utm.my innovative ● entrepreneurial ● global 66


C Identifier
 Identifier: A variable or function name made up of a letter
or underscore (_), followed by a sequence of letters
and/or digits and/or underscores.
 Case sensitive
 Can be any length, but some compilers may recognize
only a limited number of characters.
 Must not be the reserved words.
 “White space (e.g. black space, tab, new line)” is ignored
unless delineated by quotes.

www.utm.my innovative ● entrepreneurial ● global 77


C Reserved Word
 Must be lowercase
 Should never be used as identifiers.
auto defined float long static while
break do for register struct
bit double funcused return switch
case eeprom goto short typedef
char else if signed union
const enum inline sizeof unsigned
continue extern int sfrb void
default flash interrupt sfrw volatile

www.utm.my innovative ● entrepreneurial ● global 88


Variables and Constants

www.utm.my innovative ● entrepreneurial ● global 99


Variables and Constants
 Variables: Values that can be changed (RAM) Used to
Constant: Fixed Values (ROM) store data
 Stored in the limited memory of the C, and the compiler
needs to know how much memory to set aside for each
variable without wasting memory space unnecessarily.
 Variable declaration:
Reserve word indicating its type and size, followed by an
identifier
unsigned char ascii;
int clock_cycle;
double execution_time;

www.utm.my innovative ● entrepreneurial ● global 10


10
Variables and Constant Types
Type Size (Bits) Size (Bytes) Range
bit 1 - 0, 1
char 8 1 -128 to 127
unsigned char 8 1 0 to 255
signed char 8 1 -128 to 127
int 16 2 -32768 to 32767
short int 16 2 -32768 to 32767
unsigned int 16 2 0 to 65535
signed int 16 2 -32768 to 32767
long int 32 4 -2147483648 to 2147483647
unsigned long int 32 4 0 to 4294967295
signed long int 32 4 -2147483648 to 2147483647
float 32 4 1.175e-38 to 3.402e38
double 64
www.utm.my
8 9.46e -308 to 1.79e308
innovative ● entrepreneurial ● global 11
11
Variables Scope
 Accessibility of a variable within a program.
LOCAL Variable Global / External Variable
Memory spaces allocated by the Memory space that is allocated
function by the compiler
Not accessible from other Accessible by all the functions in
functions a program
Scope is limited to the functions in Unlimited scope
which they are declared
Local variable with same identifier Can be modified by any function
name can be used in multiple and will retain its value to be
functions without conflict used by other functions.
If a local variable has the same name as a global variable and is used within a
function, the local variable will be used by the function. The value of global
variable will remain untouched.
www.utm.my innovative ● entrepreneurial ● global 12
12
Constants
 Constant: Fixed Values and never be changed
 Stored in the program code space (ROM) rather than in the
limited variable data storage space (RAM) to save limited
data memory space.
 Can be in the form of number, character or a string of text.
e.g. Z = 2032 * y;
x = ‘A’;
code = “SMBE2032”;
const char c = 20;

www.utm.my innovative ● entrepreneurial ● global 13


13
Numeric Representation
Representation Prefix Example
Decimal - 1234
Binary 0b 0b10101111
Hexadecimal 0x 0xFF
Octal 0 0765

Representation Suffix Example


Unsigned integer U 10000U
Long integer L 99L
Unsigned long integer UL 99UL
Floating point F 3.214F
Printable Character ‘‘ ‘a’, ‘A’, ‘\141’, ‘\x61’
www.utm.my innovative ● entrepreneurial ● global 14
14
Numeric Representation
Nonprintable Character Representation Equivalent Hex Value
BEL ‘\a’ ‘\x07’
Backspace ‘\b’ ‘\x08’
Horizontal Tab (TAB) ‘\t’ ‘\x09’
New line Feed, New line (LF) ‘\n’ ‘\x0a’
Vertical Tab (VT) ‘\v’ ‘\x0b’
NP Form Feed, New Page (FF) ‘\f’ ‘\x0c’
Carriage Return (CR) ‘\r’ ‘\x0d’
Backslash ‘\\’ ?
Single quote ‘\’’ ?

www.utm.my innovative ● entrepreneurial ● global 15


15
Ascii Code Table

www.utm.my innovative ● entrepreneurial ● global 16


16
Enumerations & Definitions
 To allow the programmer replace numbers with names or
other more meaningful phrase.
 Enumeration, enum:
• To assign sequential integer constant values to a list of identifier.
• To replace pure numbers.
 Definition, #define:
• To define constants or any macro substitution.
• Allow substitution of one text string for another
• Pre-processor directive: Happens before the actual compilation
begins.
www.utm.my innovative ● entrepreneurial ● global 17
17
Enumerations & Definitions
 Example:
#include<stdio.h>
#define PORTB "DIGITAL PORT"
#define leds 8

void main()
{
enum { red_led_on = 1, green_led_on, both_leds_on };

printf("green_led_on = %d\n", green_led_on);


printf("Number of LEDS = %d\n", leds);
printf("PORT B is %s\n", PORTB);
}

www.utm.my innovative ● entrepreneurial ● global 18


18
Storage Classes: auto, static and register
Automatic (auto) Static (static) Register (register)
Default class Same as auto
Uninitialized when it is Allocated in global Use an actual machine
declared and allocated in memory space. register in the
memory space (RAM) microprocessor as the
variable
Memory space is Initialized to zero for Intent of speeding up
released when the the first time the a particular process
function is exited, function is entered, by reducing the
meaning the values will and it retains its value number of machines
be lost and if the when the function is cycles required to
function is re-entered exited. access the variable.
auto int value_1; static int value_2; register char value_3;
int value_1;
www.utm.my innovative ● entrepreneurial ● global 19
19
Type casting
 Temporary force the type and size of the variable.
 Allow the previously declared type to be overridden for the
duration of the operation being performed.
 Important when the arithmetic operations are performed
with variable of different sizes.
int x=12; // a signed integer, 16-bit integer (-32768 to +32767)
char y; // a signed, 8-bit character (-128 to +127)

y = (char)x + 3; // x is converted to a character and then 3 is added,


// and the value is then placed into y.
x = (int)y; // y is extended up to an integer, and assigned to x.

www.utm.my innovative ● entrepreneurial ● global 20


20
Operators

www.utm.my innovative ● entrepreneurial ● global 21


21
Assignment and Operators
 Assignment operator (=)
 A value assigned to a variable can be a constant, a variable
or an expression.
 Parenthesis (): Improve code readability and determine
priority
Arithmetic Operators C Symbol Relational Operators C Symbol
Multiply * Is Equal to ==
Divide / Is Not Equal to !=
Modulo % Less Than <
Addition + Less Than or Equal to <=
Subtraction or Negation - Greater Than >
www.utm.my
Greater Than or Equal to >=
innovative ● entrepreneurial ● global 22
22
Assignment and Operators
Bitwise Operators C Symbol Logic Operators C Symbol
One’s Complement ~ AND &&
Left Shift << OR ||
Right Shift >> NOT !
AND &
 TRUE – Represented by a
Exclusive OR ^
nonzero value
OR (Inclusive OR) |
 FALSE – by a zero value
 Bitwise AND and OR are
useful in dealing with
parallel ports - masking and
bitwise port control
www.utm.my innovative ● entrepreneurial ● global 23
23
Increment, Decrement and Compound
Compound Equivalent
Assignment Assignment
Increment/Decrement C Symbol Operator Example
Operators (Example) a += 3 a=a+3
Post-Increment X++ a -= 5 a=a–5
Pre-Increment ++X a *= 2 a=a*2
Post-Decrement Y-- a /= 4 a=a/4
Pre-Decrement --Y a%=9 a=a%9
a |= 7 a = a OR 7
 Post-Operation: An operation
is executed after the a &= 6 a = a AND 6
expression has been resolved.
a ^= 8 a = a XOR 8
 Pre-Operation: An operation is
executed before the a <<= 2 a = a << 2
expression was resolved. a >>= 3 a = a >> 3
www.utm.my innovative ● entrepreneurial ● global 24
24
Memory Accessing Operators
Operator Meaning Example Result
& Address of &x Memory address of variable x
* Pointer variable 2 meanings:
declaration or int *p; • Pointer variable declaration
Indirection *p = 3; • The content of an object (or function)
pointed by p.
[] Array element x[i] *(x+i), the element with index i in the array
x.
. Member of a s.x The member named x in the structure or
structure or union union s
-> Member of a p->x The member named x in the structure or
structure or union union pointed to by pointer variable p.

www.utm.my innovative ● entrepreneurial ● global 25


25
Conditional Operator (? :)

expression_A ? expression_B : expression_C;

 If expression_A returns TRUE, execute expression_B,


else execute expression_C

 Example: Assume x = 5 and y = 2. What is the output of:


( x && y ) ? printf(“True”); printf(“False”);
(x & y ) ? printf(“True”); printf(“False”);
( x || y ) ? printf(“True”); printf(“False”);
(x|y) ? printf(“True”); printf(“False”);

www.utm.my innovative ● entrepreneurial ● global 26


26
Operator Precedence
Name Level Operators Grouping
Primary 1 (High) () . [] -> Left to right
Unary 2 ! ~ (type) * & ++ -- sizeof Right to left
Binary 3 * / % Left to Right
Arithmetic 4 + - Left to right
Shift 5 << >> Left to right
Relational 6 < <= > >= Left to right
Equality 7 == != Left to right
Bitwise 8 & Left to right
Bitwise 9 ^ Left to right
Bitwise 10 | Left to right
Logical 11 && Left to right
Logical 12 || Left to right
Conditional 13 ? : Right to left
Assignment 14 (low) = += -= /= *= %= <<= >>= &= ^= |= Right to left
 Instead of memorize this table, use parenthesis () to guarantee the order process.
www.utm.my innovative ● entrepreneurial ● global 27
27
Control Statement

www.utm.my innovative ● entrepreneurial ● global 28


28
Control Statement
 To control the flow of execution of a program
• if/else: To steer or branch the operation in one of two directions.
• while, do/while, for: To control the repetition of a block of
instructions
• switch/case: To allow a single decision to direct the flow of the
program to one of many possible blocks of instruction in a clean
and concise fashion.

www.utm.my innovative ● entrepreneurial ● global 29


29
If branch
if (condition)
{
statement1;
statement2;
…..
}

OR

 Try to create a good programming habit


if (condition) to always include the { } though the if
statement; block only consists of single statement.
www.utm.my innovative ● entrepreneurial ● global 30
30
If…else branch
if (condition)
{
statement1;
statement2;
…..
}
else
{
statement1; if (condition)
statement2; statementT;  Try to create a good programming
….. habit to always include the { }
else
} though the if block only consists
statementF;
of single statement.
www.utm.my innovative ● entrepreneurial ● global 31
31
If…else if … else branch
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
…..
else if (condition_n-1)
statementn-1;
else
statementn;

www.utm.my innovative ● entrepreneurial ● global 32


32
Switch…case statements
switch (condition)
{
case condition1:
statements1;
break;
case condition2:
statements2;
break;

case conditionn-1:
statementsn-1;
break;
default:
statementsn;
break;  The condition could only accept
}
either integer or char value.
www.utm.my innovative ● entrepreneurial ● global 33
33
While loop
while (condition)
{
statement1;
statement2;
…..
}

OR
 Try to create a good programming
while (condition) habit to always include the { } though
statement; the while loop only consists of single
statement.
www.utm.my innovative ● entrepreneurial ● global 34
34
Do…While loop
do
{
statement1;
statement2;
…..
} while (condition);

OR

do  Try to create a good programming


statement; habit to always include the { } though
while (condition); the while loop only consists of single
statement.
www.utm.my innovative ● entrepreneurial ● global 35
35
For loop
for (init; condition; update)
{
statement1;
statement2;
…..
}  Initialization: only execute once at the
start of the loop
OR  Conditional: Tested and if result
returns TRUE, then statements are
for (init; condition; update) executed.
statement;
 Update: Execute at the end of each
loop iteration
www.utm.my innovative ● entrepreneurial ● global 36
36
For loop
for (init; condition; update)
{
statement1;
statement2;
…..
}

Equal with:

init;
while (condition)
{
statement1;
statement2;
…..
update;
}

www.utm.my innovative ● entrepreneurial ● global 37


37
break, continue, and goto
 break, continue, and goto: To modify the execution of the for, while,
do/while, and switch statements.
 break:
• To exit from a for, while, do/while, or switch statement entirely.
• If the statements are nested one inside the other, the break statement will exit
only from the immediate block of statements.
 continue:
• Allow the program to start the next iteration of a while, do/while, or for loop.
• Quit the following statements after continue but restart the loop again as next
iteration.
 goto: Literally “jump” execution of the program to a label marking
the next statement to be executed.

www.utm.my innovative ● entrepreneurial ● global 38


38
break

www.utm.my innovative ● entrepreneurial ● global 39


39
continue

www.utm.my innovative ● entrepreneurial ● global 40


40
break vs continue
break continue
A break can appear in both switch and A continue can appear only in loop (for, while, do)
loop (for, while, do) statements. statements.
A break causes the switch or loop A continue doesn't terminate the loop, it causes the
statements to terminate the moment it loop to go to the next iteration. All iterations of the
is executed. Loop or switch ends loop are executed even if continue is encountered.
abruptly when break is encountered. The continue statement is used to skip statements in
the loop that appear after the continue.
The break statement can be used in The continue statement can appear only in loops.
both switch and loop statements. You will get an error if this appears in switch
statement.
When a break statement is When a continue statement is encountered, it gets
encountered, it terminates the block the control to the next iteration of the loop.
and gets the control out of
the switch or loop.
A break causes the innermost enclosing A continue inside a loop nested within a
loop or switch to be exited immediately. switch causes the next loop iteration.

www.utm.my innovative ● entrepreneurial ● global 41


41
Functions

www.utm.my innovative ● entrepreneurial ● global 42


42
Functions
 Function / subroutine / procedures: an encapsulation of a block
of statements that can be used more than once in a program.
 Development of a “library”
• Modularity
• Reusability
• Save time and maintains stability
 A function may not receive any argument or parameter or
return a value: void.
 A function may accept multiple parameters, but it can only
return one, default type is int.

www.utm.my innovative ● entrepreneurial ● global 43


43
Function Prototype Declaration
 Normally declared in a “header.h” file then include by a
“program.c” file.
e.g.
/* program.c */
#include “header1.h” //user header file
#include <header2.h> // system header file
 Function declaration:
return_type function_name (type arg1, type arg2, …type argn);

float arg1 float


int Output / int
char arg2 function_name char
Return value
double : (only allow one) double
etc argn etc

www.utm.my innovative ● entrepreneurial ● global 44


44
Function Prototype Declaration
 e.g. /* header1.h */
int func_1 (int a, double b, char c); // argument type is compulsory
// OR
int func_1 (int, double, char); // argument name is optional
void func_2 (void);

(integer) a

(double) b func_1 int func_2


(char) c

 C DOES NOT allow multiple function prototype declaration


with same function name
e.g. /* header1.h */
int func_1 (int, double, char);
int func_1www.utm.my
(double, double, char);innovative
// illegal
● entrepreneurial ● global 45
45
Function Body Definition
 Normally declared in a “header.c” file while include the function prototype
declaration of “header.h” file.
e.g.
/* header1.c */
#include “header1.h”

 Function definition:
return_type function_name (type arg1, type arg2, …type argn)
{
statement1;
statement2;
…….
statementn;

return (value);
}

www.utm.my innovative ● entrepreneurial ● global 46


46
Function Body Definition
 The number, type and the sequence of the argument during
function definition or function call MUST BE MATCHED with
function declaration.
 e.g: /* header1.h */
int func1 (int a, double b, char c);
/* header1.c */
#include “header1.h”
int func1 (int a, double b, char c) // match!
{ … }
char func1 (double a, double b, char c) // type of agrument mismatch!
{ … }
int func1 (double b, int a, char c) // type and sequence of arguments mismatch!
{ … }
int func1 (char c) // # of argument mismatch!
{ … }
www.utm.my innovative ● entrepreneurial ● global 47
47
Complete Example
/* ALU.h */ /* main.c */
int addition (int a, int b); #include “ALU.h”
double multiplication (double a, double b);
int main()
/* ALU.c */ {
#include “ALU.h” int a = 3, b = 5, c = 0;
int x = 3.45, y = 4.12, z = 0.0;
int addition (int a, int b)
{ int c; c = addition (a, b);
c = a + b; z = multiplication (x, y);
return c; }
}

double multiplication (double a, double b)


{ int c;
c = a * b;
return c;
}
www.utm.my innovative ● entrepreneurial ● global 48
48
Recursive Function
 A function that calls itself.
 Example: Calculating factorials: n! = n * (n-1)!
int fact (int n)
{
if (n==0)
return 1;
else
return ( n * fact (n-1));
}

 Possible applications: factorials, quick sorts, and linked-lists


searches.

www.utm.my innovative ● entrepreneurial ● global 49


49
Pointers and Arrays

www.utm.my innovative ● entrepreneurial ● global 50


50
Pointers
 Pointers: Variables that contain the address or location of a
variable, constant, function or data object.
 Allocates an area in memory large enough to hold the
machines address of the variable (not according to the data
width)
 Dealing with the address of the variable it is pointing to, not
the value of the variable itself.
 * : Indirection or dereferencing operator, to gain access to
the data located at the address contained in the pointer.
 &: Address operator
www.utm.my innovative ● entrepreneurial ● global 51
51
Pointers
 e.g.
char *p; // p is a pointer to a character

char a, b; // a and b are normal character variables

p = &a; // p stores the address of variable a and


// pointing to a

b = *p; //b equals the contents pointed to by p, b = a

*p = 5; //the contents pointed to by p stores 5, a = 5

www.utm.my innovative ● entrepreneurial ● global 52


52
Pointers Memory Address Memory (RAM) Variables
0x1000 0x35 a
0x1001 0x36

p = &a
char *p; 0x1002 0x78 b
0x1003 0x8A
char a, b;
0x1004 0x10 *p
0x1005 0x00
p = &a;
BEFORE
b = *p;
*p = 5; Memory Address Memory (RAM) Variables
0x1000 0x05 (*p = 5) a
0x1001 0x36

p = &a
0x1002 0x35 (b = *p) b
0x1003 0x8A
0x1004 0x10 *p
0x1005 0x00

www.utm.my AFTER
innovative ● entrepreneurial ● global 53
53
Pointers
 Pointers are effectively addresses, they offer the ability to
move, copy, and change memory in all sorts of ways.
int *iptr; // a pointer point to a integer variable
long *lptr; // a pointer point to a long variable

iptr = iptr + 1; // moves the pointer to the next integer


// (2 bytes away)
lptr = lptr + 1; // moves the pointer to the next long
// integer (4 bytes away)
iptr++; // moves the pointer to the next integer
// (2 bytes away)
--lptr++; // moves the pointer back to the preceding
// long integer location (-4 bytes)

www.utm.my innovative ● entrepreneurial ● global 54


54
Pointers
 Other eg: Same priority, evaluate from left to right
char c;
char *p;

c = *p++; //assign c the value pointed to by p, and then


// increment the address p
c = *++p; // increment the address p, then assign c the
// value pointed to by p
c = ++*p; // increment the value pointed to by p, then
// assign it to c, leaving the value of p untouched
c = (*p)++; // assign c the value pointed to by p, and then
// increment the value pointed to by p, leaving the
// value of p untouched

www.utm.my innovative ● entrepreneurial ● global 55


55
Pointers and Function
/* ALU.h */  Pointers can be used to extend the
void swap1 (int a, int b); amount of information returned
void swap2 (int *a, int *b); from a function.
/* main.c */
/* ALU.c */
#include “ALU.h”
#include “ALU.h”

void swap1 (int a, int b) int main()


{ int temp; {
temp = b; int a = 23, b = 35;
b = a; int *ptr_a = &a, *ptr_b = &b;
a = temp;
} swap1 (a, b); // pass by value
swap2 (ptr_a, ptr_b); // pass by pointer
void swap2 (int *a, int *b) swap2 (&a, &b); // pass by reference
{ int temp; }
temp = *b;
*b = *a; Are all these three function calls
*a = temp;
}
returns the same result?
www.utm.my innovative ● entrepreneurial ● global 56
56
Arrays
 Array: A data set of same declared type, arranged in order.
int digits[10]; // this declares an array of 10 integers
char str[20]; // this declares an array of 20 characters
 Referencing of an array elements: by an index or subscript, range
from 0 to n-1.
str[0], str[1], str[2], …….. str[19]

 Array declarations can contain initializer.


int array[5] = {5, 10, 15, 20, 25};

//what will happen if:


c = array[8]; //? – will lead to unexpected result
// outside of array boudary
www.utm.my innovative ● entrepreneurial ● global 57
57
Character Array
 Most common array type.
 Also refer as a string or character string.
char str[6];
const cstr[8] = “Hello C”;

Memory Address Memory (ROM) Variables


0x1000 ‘H’ cstr[0]
0x1001 ‘e’ cstr[1]
0x1002 ‘I’ cstr[2]
0x1003 ‘l’ cstr[3]
0x1004 ‘o’ cstr[4]
0x1005 ‘<space>’ cstr[5]
0x1006 ‘C’ cstr[6]
0x1007 \0 (null termination) cstr[7]
www.utm.my innovative ● entrepreneurial ● global 58
58
Multidimensional Arrays
 Multidimensional Array: Arrays of arrays
 Could be two, three, four, or more dimensions.
 Useful in operations such as matrix arithmetic, filters, and look-
up tables (LUTs) block_A [0] [1]

int block_A[2];
block_B [0] [0] [1]
int block_B[2][2];
int block_C[3][2][2]; [1] [0] [1]

[0] [1] [2]

block_C [0] [0] [1] [0] [0] [1] [0] [0] [1]

[1] [0] [1] [1] [0] [1] [1] [0] [1]

www.utm.my innovative ● entrepreneurial ● global 59


59
Array and Pointers
 The array name itself is treated as the address of the first
element in the array.
char stng[10];
char *p;

p = stng; // p is pointing to stng[0]


p = &stng[0]; // same as statement above

p = &stng[5]; //p is pointing to stng[5]


*p = 5; // stng[5] = 5

www.utm.my innovative ● entrepreneurial ● global 60


60
Structure and Union

www.utm.my innovative ● entrepreneurial ● global 61


61
Structures and Unions
 Used to group variables (could consist of different variable
data type) under one heading or name.
 A structure or union can be thought of as an object.
 The members of the structure or union are the properties
(variables) of that object.
 Consider as the fundamental elements in object-oriented
programming (OOP).

www.utm.my innovative ● entrepreneurial ● global 62


62
Structures
 Structure template declaration:
struct structure_name struct structure_name
{ {
type member1; type member1;
type member2; type member2;
… …
type memberX; type memberX;
}; } structure_var_name;

 Structure variable declaration:


struct structure_name var1, var2[3];
 Member operator (.) : to access a member within a structure
structure_var_name.member1;
www.utm.my innovative ● entrepreneurial ● global 63
63
Structures Examples
// Structure template declaration struct LOCATION
struct DATE {
{ int x;
int y;
int day; };
int month;
int year; struct PART
}; {
char name[20];
long int sku;
// Structure variable declaration struct LOCATION bin;
struct DATE birth_date = { 3, 9, 1980}; } widget;

// Access & modify structure member location_x = widget.bin.x;


birth_date.day = 31; location_y = widget.bin.y;
birth_date.month = 8; widget.bin.x = 30;
birth_date.year = 1978; widget.bin.y = 256;

www.utm.my innovative ● entrepreneurial ● global 64


64
Structures
 A structure can be passed to a function as a parameter as
well as returned from a function.
struct PART new_location (int x, int y)
{
struct PART temp;
temp.name = “ “;
temp.sku = 0;
temp.bin.x = x;
temp.bin.y = y;
}

widget = new_location (10,10);

www.utm.my innovative ● entrepreneurial ● global 65


65
Array of Structures
struct PART
{
char name[20];
long int sku;
struct LOCATION bin;
} widget[100];

location_x = widget[23].bin.x;
location_y = widget[23].bin.y;

widget[23].name; // the name of widget 24


widget[23].name[0]; // the 1st character in the name of
//widget 24
www.utm.my innovative ● entrepreneurial ● global 66
66
Pointer to Structure
 To use a pointer to reference the structure, eg. Passing a
pointer to a structure to a function instead of passing the
entire structure.
 Structure pointer variable declaration:
struct structure_name *structure_var_name;
 Structure pointer operator (->): To access the members of the
structure through indirection.
structure_var_name -> member;
OR
(*structure_var_name).member;
www.utm.my innovative ● entrepreneurial ● global 67
67
Pointer to Structure Example
struct LOCATION
{ // This is the location coordinates x and y
int x;
int y;
};
struct PART
{
char name[20]; // a string for the part name
long int sku; // a SKU number for the part
struct LOCATION bin; // its location in the warehouse
};
struct PART widget, *this_widget; // declare a structure and a pointer to a structure
this_widget = &widget; // assign the pointer the address of a structure

this_widget->sku = 1234; // Access a member of the structure through indirection
(*this_widget).sku = 1234; // Using the indirection operator to first locate the
// structure and then using the member operator to
// access the sku member

www.utm.my innovative ● entrepreneurial ● global 68


68
Unions
 Much like a structure, but difference in the way the memory
is allocated.
 The members of a union actually share a common memory
allocated to the largest member of that union.

union union_name union union_name


{ {
type member1; type member1;
type member2; type member2;
… …
type memberX; type memberX;
}; } union_var_name;

www.utm.my innovative ● entrepreneurial ● global 69


69
Unions
 E.g union SOME_TYPES Allocated memory:
{
char character; 4 bytes (long int datatype)
int integer;
long int long_one;
} my_space;

my_space.long_one = 0x12345678L;

Then the character and integer will also be modified

my_space.character = 0x12;
my_space.integer = 0x1234;
www.utm.my innovative ● entrepreneurial ● global 70
70
Unions
 Used as a method of preserving valuable memory space.
 Define a “scratch pad” area of memory: If there are
variables that are used on a temporary basis, and there is
never a chance that they will be used at the same time
 Used a s method of extracting smaller parts of data from a
larger data object
 The data could be byte order swapped, word order
swapped, or both.
 Could be used as a test for a compiler in order to find out
data organization in memory (big-endian or little endian)

www.utm.my innovative ● entrepreneurial ● global 71


71
Array vs. Structures
Array Structure
Collection of data elements of same Collection of data elements of
type (homogeneous). different types (heterogeneous)
Derived data type Programmer-defined data type
Any array behaves like a built-in data But in the case of structure, first we have
types. All we have to do is to declare an to design and declare a data structure
array variable and use it. before the variable of that type are
declared and used.
Allocates static memory Allocate dynamic memory
Array data are access using index. Structure elements are access using (.)
operator.
Array is a pointer to the first element of Structure is not a pointer
it
Element access takes relatively less Property access takes relatively large
time. time.

www.utm.my innovative ● entrepreneurial ● global 72


Structures vs. Union
Structure Union
Keyword: struct Keyword: union
When a variable is associated with a When a variable is associated with a union,
structure, the compiler allocates the memory the compiler allocates the memory by
for each member. considering the size of the largest memory.
Size is greater than or equal to the sum of Size of union is equal to the size of largest
sizes of its members. The smaller members member.
may end with unused slack bytes.
Each member within a structure is assigned Memory allocated is shared by individual
unique storage area of location. members of union.
The address of each member will be in The address is same for all the members of a
ascending order. This indicates that memory union. This indicates that every member
for each member will start at different offset begins at the same offset value.
values.
Altering the value of a member will not affect Altering the value of any of the member will
other members of the structure. alter other member values.
Individual member can be accessed at a time. Only one member can be accessed at a time.
Several members of a structure can initialize Only the first member of a union can be
at once. initialized.
73
www.utm.my innovative ● entrepreneurial ● global 73
typedef and sizeof operators

www.utm.my innovative ● entrepreneurial ● global 74


74
typedef
 typedef: For creating new type name with an existing type.
typedef struct
typedef unsigned char byte; { char name[20];
typedef unsigned int word; char age;
int hp_no;
} student;
byte var1;
student Jasmine;
word var2; student Wendy;

 typedef is evaluated by the compiler directly and can work


with declarations, castings, and usages that would exceed
the capabilities of the pre-processor #define.

www.utm.my innovative ● entrepreneurial ● global 75


75
sizeof
 sizeof: A compile-time feature that creates a constant value
related to the size of data object or its type (in bytes)
located in the parentheses ( ).
sizeof (typename);
sizeof(object);
 Example:
int value, x; x = sizeof(int); // this would set x=2, since an int is 2 bytes
long int array[2][3];
x = sizeof(value); // this would set x=2, since value is an int
x = sizeof(long); // this would set x=4, since a long is 4 bytes
struct record x = sizeof(array); // x = sizeof(long)*array_width*array_length
{ //= 4*2*3 = 24
char name[24];
int id_number; x = sizeof(record); // x = 24+2 for the char string + the integer
} students[100]; x = sizeof(students); // x = 100 Elements * (24 characters +
sizeof(int)), x = 100*(24+2) = 2600 !!
www.utm.my innovative ● entrepreneurial ● global 76
76
Software Development

www.utm.my innovative ● entrepreneurial ● global 77


77
Software Development Cycle

www.utm.my innovative ● entrepreneurial ● global 78


78
Programming styles, standards &
guidelines
 Readability and maintainability of the software
 A documented development process
 Project management
 Quality control and meeting outside requirements such as
ISO9001 and ISO9003
 Configuration management and revision control
 Design-rule and code-style requirements of your company or
organization
 Verification and validation processes to meet medical and
industrial requirements
 Hazard analysis
www.utm.my innovative ● entrepreneurial ● global 79
79

You might also like