0% found this document useful (0 votes)
9 views

Chapter2_Basics of C and C++_part1

Uploaded by

dang8805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chapter2_Basics of C and C++_part1

Uploaded by

dang8805
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

EE3491 - Kỹ thuật lập trình

EE3490E – Programming Techniques


Chapter 2: Basics of C and C++

Lecturer: Dr. Hoang Duc Chinh (Hoàng Đức Chính)


Department of Automation Engineering
School of Electrical and Electronics Engineering
Email: [email protected]

© HĐC 2024.1
Content

2.1. C/C++ Program Structure


2.2. Variables and Basis Data Types
2.3. Derived Data Types
2.4. User-defined data type
2.5. Control flow: Decision making
2.6. Control flow: Loop
2.7. Input/Output
2.8. Preprocessor
2.9. Bitwise operation

© HĐC 2024.1 Chapter 2: Basic of C & C++ 2


2.1. C/C++ Program Structure

Structure and fundamental components of a C/C++


program
Procedure to create an executable program:
 Create a project
 Coding style and standard
 Compile partially and fix compile errors
 Link, library usages, fix link errors
 Test and debug
Memory management

© HĐC 2024.1 Chapter 2: Basic of C & C++ 3


Program structure

#include <stdio.h> Required in every program


int main(void) Variable declaration (assigning
{ memory allocation for each
// variable declaration variable)
int firstOperand;
CPU instructions (statements)
int secondOperand;
int thirdOperand;
/* statements */
firstOperand = 1;
secondOperand = 2;
thirdOperand = firstOperand + secondOperand;
printf(“%d”, thirdOperand);

return 0;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 4


Coding style and standard

 New variable, function, types names:


 Avoid C/C++ keywords and basic types
 Usable characters: ‘A’...’Z’, ‘a’...’z’, ‘0’...’9’, ‘_’
 Uppercase and lowercase are treated differently
 Should be short but distinguishable
 Use English
 Statement ends with a semi-colon ;
thirdOperand = firstOperand + secondOperand;
 {…} is a group of statements, no semi-colon follows except
type definition
 Code structure should be hierarchized easy to read
 Provide suitable comments with /*…*/ or //
 Divide a large file into different small files

© HĐC 2024.1 Chapter 2: Basic of C & C++ 5


C Keywords

© HĐC 2024.1 Chapter 2: Basic of C & C++ 6


C++ Keywords

© HĐC 2024.1 Chapter 2: Basic of C & C++ 7


Processing a C/C++ program

Include Header, expanded macro

Object program

Executable program

© HĐC 2024.1 Chapter 2: Basic of C & C++ 8


Compiler & Linker

 The compiler checks the source program for syntax errors


and, if no error is found, translates the program into the
equivalent machine language. The equivalent machine
language program is called an object program.
 Linker combine destination files (*.obj, *.lib) to generate an
executable file *.exe
 Errors that may occurs includes:
 Undeclared functions
 Duplicated declaration of variables or functions

© HĐC 2024.1 Chapter 2: Basic of C & C++ 9


Create a new project

Break point

© HĐC 2024.1 Chapter 2: Basic of C & C++ 10


Debug

Run the program with F5

Break point

© HĐC 2024.1 Chapter 2: Basic of C & C++ 11


Debug

Run the program with F5


 Step over (run each statement), Step in (jump to the function
called), Step out (jump out of the function called)
Debugging can be done via command line by using gdb
To find errors:
 Operation, algorithm, logic errors not the syntax errors
 Errors which are not informed when executing the program
 These errors are difficult to find, thus it is required to debug in
most of the cases

© HĐC 2024.1 Chapter 2: Basic of C & C++ 12


Program Execution
Processor

Fetch Decode Read Read


Compute Write
Instruction Instruction Registers Memory

Registers

Program Data
Memory Memory

 Program Memory
 Non-volatile type
 Stores instructions in memory slots
 CPU reads and executes instructions
 Data MemoryVolatile type
 Stores temporary data in memory slots
 Very fast
 Cache, Registers, and RAM (SRAM, DRAM, DDRAM...)
© HĐC 2024.1 Chapter 2: Basic of C & C++ 13
Memory allocation of C/C++ Programs

Operating system

Other programs
Top of the stack
Code (Text) SP
n
Global variables Matrix_A
f
Free memory space (Heap) k
i
Stack (arguments, local count
variables)
a

Free memory space (Heap)

© HĐC 2024.1 Chapter 2: Basic of C & C++ 14


2.2 Variables and Data Types

Statement = data + operator + …


Data is represented via variables or constants with data
type
Number Systems
 Information in computer is represented in base 2, or binary
number system which has only 2 digits: 0 an 1.
 Binary numbers can be stored in
memory as a sequence of bits,
called a word
 The number of words available
in address space memory is
referred to as the memory space,
or address space. Memory Diagram: Address Space = 8,
Word Size = 16
© HĐC 2024.1 Chapter 2: Basic of C & C++ 15
2.2.1 Data Types

Type Typical Bit Width Typical Range


char 1 byte -127 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -127 to 127
int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned int 4 bytes 0 to 4,294,967,295
signed int 4 bytes -2,147,483,648 to 2,147,483,647
short int 2 bytes -32,768 to 32,767
unsigned short int 2 bytes 0 to 65,535
signed short int 2 bytes -32,768 to 32,767
long int 8 bytes -2,147,483,648 to 2,147,483,647
signed long int 8 bytes same as long int
unsigned long int 8 bytes 0 to 4,294,967,295
long long int 8 bytes -(2^63) to (2^63)-1
unsigned long long int 8 bytes 0 to 18,446,744,073,709,551,615

© HĐC 2024.1 Chapter 2: Basic of C & C++ 16


Data Types (cont.)

Characters Let’s find the full table and extended table yourself!

© HĐC 2024.1 Chapter 2: Basic of C & C++ 17


Data Types (cont.)

Type Typical Bit Width Typical Range


float 4 bytes
double 8 bytes
long double 12 bytes
bool (C++) - -
wchar_t 2 or 4 bytes 1 wide character

© HĐC 2024.1 Chapter 2: Basic of C & C++ 18


Data Types (cont.)

float in C

© HĐC 2024.1 Chapter 2: Basic of C & C++ 19


Basic operators

Operator Symbols Integer Real Bool


Assignment = X X X
Arithmetic +, -, *, /, +=, -=, X X X
*=, /=
%, %= X X
++, -- X X
Relational >, <, >=, <=, ==, X X X
!=
Logical &&, ||, ! X X X
Bitwise &, |, ^, ~, &=, X X
|=, ^=
Bit shift <<,>>, <<=, >>= X X
Conditional ?: X X X
Power Not available

© HĐC 2024.1 Chapter 2: Basic of C & C++ 20


2.2.2 Variable declaration

Variable name

Right Wrong Right but …


rectangleWidth 10TimesLength a1
rectangle_Width My Variable l
rectangle_width int O

© HĐC 2024.1 Chapter 2: Basic of C & C++ 21


Variable declaration

int months;
 Proper values: 1, 17, -32, 0 Not like these 1.5, 2.0, ‘A’
double pi;
 Values are numbers with decimal point: 3.14, -27.5, 6.02e23,
5.0 Not like this 3
char first_initial, marital_status;
 Represent the character of the keyboards: ‘a’, ‘b’, ‘M’, ‘0’ , ‘9’ ,
‘#’ , ‘ ’ Not like this “Bill”
Variable can be declared with initial values:
int month = 1;
double weight = 62.6;
char c = “N”;

© HĐC 2024.1 Chapter 2: Basic of C & C++ 22


Variable declaration

C: All the variables must be declared at the beginning of


a function/program
C++: Variables can be declared when needed
Classification:
 Global variables: declared outside the functions, stored in the
program memory allocation
 Local variables: declared within the function body, store in the
stack
 Parameters/ arguments: declared together with the function in
the parameter list

© HĐC 2024.1 Chapter 2: Basic of C & C++ 23


Variable declaration

Global variable

Local variables

Local variables can


be the same name as
they are in different
scopes and unrelated

Paramter

© HĐC 2024.1 Chapter 2: Basic of C & C++ 24


Variable declaration

extern: declare to use a global variable which has


been defined in another file

static: stored in program data memory


 local static variables: not allow to access outside the function
 global static variables: not allow to access from another file

© HĐC 2024.1 Chapter 2: Basic of C & C++ 25


Example

 Convert temperature units from Fahrenheit to Celsius


#include <stdio.h>

int main(void)
{
double fahrenheit, celsius;

celsius = (fahrenheit - 32.0) * 5.0 / 9.0;

return 0;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 26


Example

 Convert temperature units from Fahrenheit to Celsius


#include <stdio.h>

int main(void)
{
double fahrenheit, celsius;
printf("Enter a Fahrenheit temperature: ");
scanf("%lf", &fahrenheit);
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
printf("That equals %f degrees Celsius.", celsius);
return 0;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 27


Example

#include <stdio.h>

int main(void)
{
double fahrenheit, celsius;
printf("Enter a Fahrenheit temperature: ");
scanf("%lf", &fahrenheit);
celsius = fahrenheit - 32.0;
celsius = celsius * 5.0 / 9.0;
printf("That equals %f degrees Celsius.", celsius);
return 0;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 28


2.2.3 Further discussions

Accurate rule is required to understand mathematical


operations

Arithmetic operations in computer is not always precise


may be 0.99999998213
Division of two int number may give a different result
from expectation
2 / 3 is 0 in C

© HĐC 2024.1 Chapter 2: Basic of C & C++ 29


Why int

Sometimes, only int number is suitable


 “slot 15” instead of “slot 14.9999999”
Number with type double may not be accurate when
representing an integer
 Mathematically: 3 * 15 * (1/3) = 15
 Computer: 3.0 * 15.0 * (1.0/3.0) may be 14.999999997
And…
 Operations with double numbers are usually slower than that of
int
 Size of double type is larger than that of int

© HĐC 2024.1 Chapter 2: Basic of C & C++ 30


Mathematical expression

Mathematical formula

An operation in C
(- b + sqrt (b*b - 4.0*a*c) ) / (2.0*a)

© HĐC 2024.1 Chapter 2: Basic of C & C++ 31


Type conversion

What is the result of 2 * 3.14 ?


As mentioned earlier, the compiler converts int into
double implicitly in this case
int + double double + double
2 * 3 * 3.14 (2*3) * 3.14
6 * 3.14 6.0 * 3.14
18.84
One should avoid operations containing variables with
different types
 Instead, we can do like this: 2.0 / 3.0 * 3.14

© HĐC 2024.1 Chapter 2: Basic of C & C++ 32


Type conversion

int total, count;


double avg;

total = 97; Implicitly convert type

count = 10;

avg = total / count; /*avg is 9.0*/

total = avg; /*BAD*/

© HĐC 2024.1 Chapter 2: Basic of C & C++ 33


Type compatibility and conversion

Types are compatible automatically converted


 Between integer types (Take note on range!!!)
 Between real types (Take note on accuracy!!!)
 Between integer and real (Take note on both range and
accuracy!!!)
 Bool to integer and real: true 1, false 0
 Integer, real to bool: true, false
If errors or warnings, it would require to perform type
casting, e.g.:
i = int (2.2) % 2;
j = (int) 2.2 + 2; // C++

© HĐC 2024.1 Chapter 2: Basic of C & C++ 34


Type casting

Type casting is used to convert data type of a value


Syntax: (type) expression
Examples:
(double) myage
(int) (balance + deposit)
Attention: type casting does not change the way of
calculation in an operation

© HĐC 2024.1 Chapter 2: Basic of C & C++ 35


Examples of type conversion

int total, count ;


double avg;
total = 97 ; Implicitly convert type
count = 10 ;
/*avg is 9.0*/ Type casting
avg = total / count;
/*avg is 9.7*/
avg = (double) total / (double) count;
/*avg is 9.0*/
avg = (double) (total / count);

© HĐC 2024.1 Chapter 2: Basic of C & C++ 36


Type conversion

© HĐC 2024.1 Chapter 2: Basic of C & C++ 37


Type conversion

© HĐC 2024.1 Chapter 2: Basic of C & C++ 38


Data types in C

All variables, values, operations must have their types


Now: always remember types of all the quantities in
your program

© HĐC 2024.1 Chapter 2: Basic of C & C++ 39


Literals

Types Values

© HĐC 2024.1 Chapter 2: Basic of C & C++ 40


Portability

Compilers for microcontrollers may consider int as 16


bit or 32 bit number depending on the microcontroller
C Compiler may read it:
 From left to right
 From right to left

© HĐC 2024.1 Chapter 2: Basic of C & C++ 41


Endianness

Endianness defines the order in which bytes that


represent large numerical values are stored in memory.
Two types:
 Big-endian: The most significant byte is stored first.
 Little-endian: The least significant byte is stored first.
 Bi-endian: Hardware supports switchable endianness.

© HĐC 2024.1 Chapter 2: Basic of C & C++ 42


Endianness

Big-endian: The most significant byte is stored first.


The 0x01020304 32-bit value is stored at the ptr address
as follows:
Offset in memory Value
ptr 0x01
ptr + 1 0x02
ptr + 2 0x03
ptr + 3 0x04

Examples of big-endian architectures are AVR32 and


Motorola 68000.

© HĐC 2024.1 Chapter 2: Basic of C & C++ 43


Endianness

Little-endian: The least significant byte is stored first.


The 0x01020304 32-bit value is stored at the ptr address
as follows:
Offset in memory Value
ptr 0x04
ptr + 1 0x03
ptr + 2 0x02
ptr + 3 0x01

The x86 architecture is little-endian.


Bi-endian: Hardware supports switchable endianness.
Some examples are PowerPC, ARMv3, and the
preceding examples.

© HĐC 2024.1 Chapter 2: Basic of C & C++ 44


Endianness

 Endianness is particularly essential when exchanging data with other


systems.
 E.g.: If a developer sends the 0x01020304 32-bit integer as is, it may be
read as 0x04030201 if the endianness of the receiver does not match the
endianness of the sender.
 This C++ snippet can be used to determine the endianness of a system:
#include <iostream>
int main() {
union {
uint32_t i;
uint8_t c[4];
} data;
data.i = 0x01020304;
if (data.c[0] == 0x01) {
std::cout << "Big-endian" << std::endl;
} else {
std::cout << "Little-endian" << std::endl;
}
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 45


Alignment

Processors don't read and write data in bytes but in


memory words—chunks that match their data address
size.
32-bit processors work with 32-bit words, 64-bit
processors with 64-bit words, and so on.
Reads and writes are most efficient when words are
aligned—the data address is a multiple of the word size.
E.g.: for 32-bit architectures
 0x00000004 address is aligned,
 0x00000005 is unaligned

© HĐC 2024.1 Chapter 2: Basic of C & C++ 46


Alignment

Compilers align data automatically to achieve the most


efficient data access.
When it comes to structures, the result may be surprising
for developers who are not aware of alignment:
struct {
uint8_t c;
uint32_t i;
} a = {1, 1};
std::cout << sizeof(a) << std::endl;

© HĐC 2024.1 Chapter 2: Basic of C & C++ 47


Fixed-width integer types

 The size of fundamental data types, such as char, short, or


int, is architecture-dependent
 To make the code portable, embedded developers often use
fixed-size integer types that explicitly specify the size of a
data field.
 The most commonly used data types are as follows:
Width Signed Unsigned
8-bit int8_t uint8_t
16-bit int16_t uint16_t
32-bit int32_t uint32_t

 size_t is a special data type to represent the offset and data


sizes in an architecture-independent way when using pointer.

© HĐC 2024.1 Chapter 2: Basic of C & C++ 48


Summary

Write a program as clear as possible


The program should be simple; complex operations need
to be represented by simple statements
Use parentheses to identify the order priority of
operators to avoid confusion if necessary
Type casting need to be clarified by programmers to
prevent implicitly type conversion in operations or
assignments
Pay attention in data type when writing operations
Be careful with architecture-dependent data types

© HĐC 2024.1 Chapter 2: Basic of C & C++ 49


2.3. Derived Data Types

Enumeration
Constant
Pointer
Array
Reference (C++)

© HĐC 2024.1 Chapter 2: Basic of C & C++ 50


2.3.1 Enumeration
 Purposes:
 Similar to integer, but need to limit the scope of usage
 Convenient to use with name integer constant
 Examples:
enum Color {Red, Green, Blue};
enum WeekDay{
Mon = 2,
Tue, Wed, Thu, Fri, Sat,
Sun = 1};
enum MotorStates{
DI_MOTOR1_STARTED= 0x01,
DI_MOTOR1_RUNNING= 0x02,
DI_MOTOR2_STARTED= 0x04,
DI_MOTOR2_RUNNING= 0x08,
DI_PUMP1_STARTED= 0x10,
DI_PUMP1_RUNNING= 0x20,
DI_OVERLOADED= 0x40,
DI_VALVE1_OPENED= 0x80
};

© HĐC 2024.1 Chapter 2: Basic of C & C++ 51


Enumeration usage
/* C version */
void main() {
enum Color c = Red; /* c = 0 */
enum WeekDay d = Tue; /* d = 3 */
int i=c, j=d; /* j=0, i=3 */ C: Similar to an 8
enum Color c2 = i+1; /* c2 = 1 */
int di1= 0x01; /* OK, but... */ bit integer
int di2= DI_MOTOR1_STARTED; /* this is better */
++c; /* c = 1 */
}
// C++ version */
void main() {
enum Color c = Red; // c = Red
WeekDay d = Tue; // OK, d = Tue
int i=c, j=d; // j=0, i=3
Color c2 = i+1; // Error!
Color c3 = Color(i+1); // OK, c3 = Green
C++: Not the same
int di1= 0x01; // OK, but... as an integer!
int di2= DI_MOTOR1_STARTED; // this is better
++c; // Error!
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 52


2.3.2 Constants

 A variable with an unchanged value


 Two simple ways in C++ to define constants:
 Using #define preprocessor, e.g.: #define pi 3.14
 Using const keyword, e.g.: const float pi = 3.14;
Is there the 3rd way?
 Example:
void main() {
const double pi = 3.1412; // initializing is OK!
const int ci= 1; // initializing is OK!
ci = 2; // error!
ci = 1; // error, too!
int i = ci; // const int is a subset of int
const Color cc = Red;
cc = Green; // error
const double d; // potential error
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 53


2.3.3 Pointer

Pointer is a variable whose value is an address of a


memory location (which is another variable or a
function)
int i = 1; 1024: 1
int* p = &i;// p has the address of i i
*p = 2;// i = 2
int j; 1024:
p = &j;// now p has the address of j
*p = 3;// j = 3, i remains 2 &i

1025: 3 1025: -8589 1024: 2 1024: 1

j, *p j, *p i, *p i, *p

1025: 1025: 1024: 1024:

p, &j p, &j p, &i p, &i

© HĐC 2024.1 Chapter 2: Basic of C & C++ 54


Pointer usage example
void main() {
int i = 0;
int* p = &i; // p refers to the addesss of i
int j = *p; // j = 0
*p = 2;// now i = 2
p = &j;// now p contains the addess of j
*p = 3;// now j = 3, i remains 2
double d = i; // OK, intis compatible to double
p = &d;// error, int* isn’t compatible to double*
p = (*int)&d; // no compile error, but dangerous,
// meaningless type conversion!
double* pd=0; // p contains the address 0
*pd = 0;// no compile error, but fatal error
pd = &d;// OK
double* pd2; // p refers to an uncertain address
*pd2= 0;// fatal error
pd2= &d;// OK, pd and pd2refer to the same addr.
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 55


Pointer summary

 Pointer is a variable which contain the address of the first byte of


another variable, it is used to access that data indirectly
 If the pointer is declared without initialization, its address is
undefined (random)
 The pointer’s value (which is a memory location address) can be
changed, the pointer can represent different variable at different
moment
 The operator “&” returns a pointer which points to a variable it
is usually used to assign a value to a pointer
 The operator “*” applies to a pointer to provide a variable whose
address is the pointer’s value so the variable’s value can be read
or changed
 Never use the operator “*”, if the pointer have not been assigned
to a memory address that can be controlled by the program

© HĐC 2024.1 Chapter 2: Basic of C & C++ 56


2.3.4 Array

A data structure with the following features:


 A fixed number of elements
 All the elements are the same type
 The elements are in sequence in the memory stack
 It is possible to access each element by its index or address
Index 0 1 2 N-1

First address Last address

First address - Last address = N * size of an element

© HĐC 2024.1 Chapter 2: Basic of C & C++ 57


Array declaration

Number of elements (array size) in an array must be an


integer constant
type name[size]; Declaration

size must be integer

E.g.: double sensor[7];


 sensor is a real array with 7 elements (size = 7)
 sensor[0], sensor[1], ... , sensor[6] are elements of sensor
array, each elements are of type double
 0, 1, ... , 6 are indexes of the array
 Maximum and minimum of the indexes are array bounds, e.g. 6
and 0 in this case

© HĐC 2024.1 Chapter 2: Basic of C & C++ 58


Example

Sensor values of 7 readings


 Set name: sensor
 Indexing: 0 to 6

0 3.0 In C:
1 3.8 sensor[0] = 3.0;
double 1.7
.
sensor[7]; . 2.0 sensor[6] = 3.2;
. 2.5 2.0*sensor[3] = 4.0;
2.1
6 3.2 ...

© HĐC 2024.1 Chapter 2: Basic of C & C++ 59


Array declaration (cont.)

Rules: if N is the array size, the indexes are 0 .. N-1


Examples:
sensor[i+3+k] /* OK as long as 0  i+3+k  6 */
Index is an integer
sensor[0]
Or can be represented as a complex operation
sensor[(int) (3.1 * fabs(sin (2.0*PI*sqrt(29.067))))]

© HĐC 2024.1 Chapter 2: Basic of C & C++ 60


Array declaration (cont.)

Declaration without initialization:


int a[3];
enum {index = 5};
double b[index];
const int N = 2;
char c[N]; // C++ only
Declaration with number of elements and initialization
of the elements
int d[3]= {1, 2, 3};
double e[5]= {1, 2, 3};
char f[4]= {0};

© HĐC 2024.1 Chapter 2: Basic of C & C++ 61


Array declaration (cont.)

Array declaration and initialization of each element,


number of elements is defined automatically
int a[]= {1, 2, 3, 4, 5};
double b[]= {1, 2, 3};
double c[]= {0};
char s[]= {‘a’};
Declaration of multi-dimension array
double M[2][3];
int X[][2]={{1,2},{3,4},{5,6}};
short T[2][2]={1,2,3,4,5,6};

© HĐC 2024.1 Chapter 2: Basic of C & C++ 62


Array usage
void main() {
int a[5]; // a has 5 elements with uncertain values
int b[5]= {1,3,5,7,9}; // 5 elements with initial values
double c[]; // error, unspecified size
double x = 1.0, y = 2.0;
double d[]= {x,y,3.0}; // 3 elements with initial values
short n = 10;
double v[n]; // error, array size must be a constant!
const int m=10;// C++ OK
double v2[m]; // C++ OK
a[0] = 1;
int i= 1;
a[i] = 2;
a[5] = 6; // no compile error, but fatal error
int k = a[5]; // no compile error, but fatal error
a = {1,2,3,4,5};// error
a = b; // error, cannot assign array
int M[2][3];
M[0][1] = 0;
M[0][2] = 1;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 63


Verification of array size

#define DATA_SIZE 7

int main() {
double sensor[DATA_SIZE];
int index;
index = 9;
...
sensor[index] = 3.5; /* Out of range?? */
if (0<=index && index<DATA_SIZE) {
sensor[index ] = 3.5;
} else {
printf(“Index %d out of range.\n”, index);
}
}
© HĐC 2024.1 Chapter 2: Basic of C & C++ 64
Special values

for (i=0; i < MAX_DATA_SIZE; i++) {


if (humidity[i] != EMPTY) {
...
}
} humidity
0 #define EMPTY -1
-1

-1
This value CANNOT
-1
be a legal value
(humidity value
-1
in this case)
-1

MAX_DATA_SIZE - 1 -1

© HĐC 2024.1 Chapter 2: Basic of C & C++ 65


Shifting array elements

/* Shift x[0], x[1], ..., x[n-1] one position


upwards to make space for a new element
at x[0]. Insert the value new at x[0].
Update the value of n. */

for (k = n; k >= 1; k = k - 1)
x[k] = x[k-1];
x[0] = new;
n = n + 1;

© HĐC 2024.1 Chapter 2: Basic of C & C++ 66


2 dimension array

An ordered set of values which have the same type


 Naming the set, numbering (indexing) elements of the set
Example: the values of 4 sensing parameters at 7 nodes

parameters
value 0 1 2 3
node 0 22 15 25 25 Expression in C:
node 1 12 12 25 20 value[0][0] = 22;
node 2 5 17 25 24
node 3 15 19 25 13 value[6][3] = 12;
node 4 2 0 25 25
2*value[3][0] = 30;
node 5 25 22 24 21
node 6 8 4 25 12

© HĐC 2024.1 Chapter 2: Basic of C & C++ 67


Declaration of 2-dimensional array

#define MAX_NODES 80
#define MAX_PARAMETERS 6
...

int value[MAX_NODES][MAX_PARAMETERS];
int num_nodes, num_params, i, j;

© HĐC 2024.1 Chapter 2: Basic of C & C++ 68


Input a 2-dimensional array

scanf(“%d %d”, &num_nodes, &num_params);


if (num_nodes <= MAX_NODES &&
num_params <= MAX_PARAMETERS) {
for (i = 0; i < num_nodes; i = i + 1)
for (j = 0; j < num_params; j = j + 1)
scanf(“%d”, &value[i][j]);
}
 Part of the array is unused

© HĐC 2024.1 Chapter 2: Basic of C & C++ 69


Special array: an array of characters

In C/C++, a character array is not a basic type, but an


array
Differentiate normal character array and array terminated
by null character ‘\0’
char city1[]= {'H','A','N',' ','O','I’};
char city2[]= "HA NOI"; // Contains 7 characters including '\0'
wchar_t city3[]= L"HÀNOI";
city2[] = “HANOI”; // error
Most of the functions in C libraries works with character
arrays terminated by null character
In C++, string is usually used instead, string class is
pre-defined in standard library

© HĐC 2024.1 Chapter 2: Basic of C & C++ 70


Pointer and Array
void main() {
int a[5]; // a has 5 elements with uncertain
values
int* p;
p = a; // p refers to a[0]
p = &a[0]; // the same as above
*p = 1; // a[0]=1
++p; // now p points to a[1]
*p = 2; // a[1]=2
p++; // now p points to a[2]
*p = 3; // a[2]=3
p += 2; // now p points to a[4]
*p = 5; // a[4] = 5
++p; // OK, no problem until we dereference it
*p = 6; // Now is a BIG BIG problem!
a = p; // error, a is like a constant pointer
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 71


Pointer and Array (cont.)

void main() {
int a[5]; // a has 5 elements with
// uncertain values
int* p = a; // p points to a[0]
p[0] = 1; // a[0]=1
p[1] = 2; // a[1]=2
p+= 2; // now p points to a[2]
p[0] = 3; // a[2]=3
p[1] = 4; // a[3]=4
p[3] = 6;// a[5]=6, Now is a BIG BIG problem!
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 72


Array summary
 An array is a set of data with the same type organized in
sequence in the memory the array elements
 An array element can be accessed via array variable together
with respected index or by using a pointer (address of each
element)
 Number of array elements is fixed (must be constant when
declaring array), it can never be changed
 An array variable (statics) is actually a constant pointer
which is assigned with the first element in the array
 It is possible to initialize element values, one should never
assign one array to another. If it is required to copy an array,
a function must be used
 Never access an array with an index which is out of range,
i.e., if N is the array size, the accessible range is 0 .. N-1
 Pointer is never an array, it can only carry array address and
be used to manage the array (either dynamic or static)
© HĐC 2024.1 Chapter 2: Basic of C & C++ 73
2.3.5. Reference (C++)

 When a variable is declared as reference, it becomes an


alternative name (alias) for an existing variable.
 Mainly used to provide parameters and return values of a
function in general, and for overloaded operators in particular.
void main() {
double d = 2.0;
double& r = d; // r represents d
double *p1 = &d, *p2 = &r;
r = 1.0; // OK, d = 1.0
double& r2; // error, r has to be assigned to a var.
double& r3 = 0;// error, too
double d2 = 0;
r = d2; // r = 0, d=0
r = 1.0; // r = d = 1, d2 =0
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 74


Reference vs. Pointer

Both are an alias for an object, and usually implemented


to hold an address of an object
Reference differs from a pointer that:
 a reference can be accessed with exactly the same syntax as the
name of an object.
 A reference always refers to the object to which it was
initialized.
 There is no ‘‘null reference,’’ and we may assume that a
reference refers to an object

© HĐC 2024.1 Chapter 2: Basic of C & C++ 75


2.3.6 Typedef

typedef create a new name for an available type, it does


not define a new type
Usage: provide a distinguish name, suitable to a specific
application, and easy to modify later
typedef float REAL;
typedef int AnalogValue;
typedef int Vector[10];
typedef AnalogValue AnalogModule[8];
typedef int* IPointer;
AnalogValue av1= 4500;
Vector x = {1,2,3,4,5,6,7,8,9,10};
AnalogModule am1= {0};
Ipointer p = &av1;

© HĐC 2024.1 Chapter 2: Basic of C & C++ 76


2.4. User-defined data type

Structure (struct): A structure is a collection of one or


more variables, possibly of different types, grouped
together under a single name for convenient handling.
More popular in C, extended usage in C++
union: A union is a variable that may hold (at different
times) objects of different types and sizes, with the
compiler keeping track of size and alignment
requirements. Less popular in both C and C++
class: only in C++, extension of struct with member
functions (will be discussed in details later)

© HĐC 2024.1 Chapter 2: Basic of C & C++ 77


2.4.1 Structure (struct)

Define struct (in or outside functions)


struct Time New type name (not duplicated)
{
int hour;
int minute;
int second; Member variables, declared
}; independently or together if same
type
struct Date {
int day, month, year;
}; Member variables can be same type
struct Student { or different ones
char name[32];
C++ struct Date birthday;
int id_number;
};

© HĐC 2024.1 Chapter 2: Basic of C & C++ 78


Declaration of struct variable

void main() {
Time classTime = {6,45,0};
Time lunchTime = {12};
Date myBirthday, yourBirthday = {30,4,1975};
Student I= {"Nguyen Van A", {2,9,1975}};
//...
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 79


Struct usage
//...
void main() {
Time classTime = {6,45,0};
Time lunchTime = {12};
Date myBirthday, yourBirthday = {1,1,1970};
Student I = {"Nguyen Van A", {5,9,2024}};
lunchTime.minute = 15;
lunchTime.hour = classTime.hour + 6;
Student U = I; // in C++ also possible: Student U(I);
U.name[11] = 'B'; // "Nguyen Van B"
U.id_number++; // 1
U.birthday.day = 30; // 30-9-1970
U.birthday.month = 4; // 30-4-1970
U.birthday = yourBirthday; // structs can be assigned
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 80


Wrong declaration and usage of struct variable

struct Time {
int hour = 0; // error, initialization not allowed
int minute, // error, use semicolon (;) instead
int second // error, missing semicolon (;)
} // error, missing semicolon (;)
//...
void main() {
Date d;
d = {11, 9, 2001}; // error, {...} is an initialization list, not a structure
Date.hour = 0; // error, Date is a type, not a var.
struct Date2{ int day, month, year; };
Date2 d2 = d; // error, Date is not compatible to Date2
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 81


Array, Pointer and Struct
 Combination of arrays, pointers and structure enable the creation and use of complex
data structure in a flexible manner
void main() {
//...
Date publicHolodays[]= {{1,5,1886},{2,9,1945},{30,4,1975}};
Date nationalDay= publicHolodays[2];
Date *p=&nationalDay;
(*p).year+= 30;// good
p->year -=30;// better
Student studentList[45];
for (inti=0; i < 45; ++i) {
studentList[i].id_number= i;
studentList[i].birthday=yourBirthday;
}
Student* pList= studentList;
while (pList< studentList+45) {
pList->id_number+= 4800;
++pList;
}
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 82


Structure summary

 Structure (struct) is used to group related data described an object, data


type can be the same or different
 Structure is defined by declaration of member variables. The definition
is not to define specific variables, thus, does not initialize the variables
 Size of structure total size of all the member variables
 A member variable of a structure can be accessed via structure variable
name, (.) operator, and member variable name
 Structures can be nested, the structure can contain an array, an array can
also have elements which are structures, etc.
 Variables with the same structure type can be assigned to each other, or
one can be used to initialize another (different from arrays)
 Pointers can also be used to access structure via (*.) and (->)
 Two structure types which are defined the same are still different
structures

© HĐC 2024.1 Chapter 2: Basic of C & C++ 83


2.4.2 Union

Define union (similar to struct)

union SignalValue { New type name (not duplicated)


unsigned short word;
unsigned char byte;
float real; Member variables
double lreal;
};

© HĐC 2024.1 Chapter 2: Basic of C & C++ 84


Example of Union
enum SignalType {BINARY_8, BINARY_16, ANALOG_1, ANALOG_2};
union SignalValue {
unsigned short word;
unsigned char byte;
float real;
double lreal;
};
struct Signal {
SignalType type;
SignalValue value;
};
void main() {
SignalValue B,W;
B.byte = 0x01;
W.word = 0x0101;
unsigned char b = W.byte; // OK, the lower byte
float f = W.real; // meaningless
Signal DI1 = {BINARY_8, 0x11};
Signal AI1 = {ANALOG_1,{0}};
Signal AI2;
AI2.type = ANALOG_2;
AI2.value.lreal = 145.67;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 85


Example of Union
#include <stdio.h>
union test1 {
int x;
int y;
} Test1;
union test2 {
int x;
char y;
} Test2;

union test3 {
int arr[10];
char y;
} Test3;
int main() {
printf(“sizeof(test1) = %lu, sizeof(test2) = %lu, sizeof(test3) = %lu,
sizeof(Test1), sizeof(Test2), sizeof(Test3));

return 0;
}

© HĐC 2024.1 Chapter 2: Basic of C & C++ 86


Union summary

 A union is a variable that may hold (at different times)


objects of different types and sizes, with the compiler
keeping track of size and alignment requirements.
 Unions provide a way to manipulate different kinds of data in
a single location of storage, without embedding any
machine-dependent information in the program.
 Members of a union are independent
 Size of a union size of the largest variable
 Similar declaration to that of struct but different meaning
 Same way of accessing member variables as struct, i.e. direct
variables or via a pointer
 A union can contain struct or vice versa, a union can also
contain arrays or elements of an array can be unions

© HĐC 2024.1 Chapter 2: Basic of C & C++ 87


Union vs Struct

Structure (struct) Union


Keyword struct union
Size Each member is allocated its own Compiler allocates the memory by
memory space. Size of struct is considering the largest size of the
greater than or equal to the sum of largest variable. Thus, size of union is
sizes of its members equal to size of the size of the largest
member
Memory Each member within a structure is Memory allocation is shared by
assigned unique storage area of individual members
location
Value Altering the value of a member Altering the value of any member will
altering does not affect others alter others’ values

Accessing Individual member can be Only one member can be accessed at a


member accessed any time time
Initialization Several members of a structure Only the first member of a union can be
of members can be initialized at once initialized

© HĐC 2024.1 Chapter 2: Basic of C & C++ 88


To be continued

You might also like