software development with c and c++

42
Software Development with C and C++ Leon Liang

Upload: others

Post on 23-Dec-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Software Developmentwith

C and C++

Leon Liang

Self-introduction• English name: leon liang

• Chinese name: 梁良

• Have been teaching CS courses over 15yrs

• E-mail:[email protected]

• Room: 8300

Module Introduction

• 12 weeks to learn

• 1 hour lectures and 2 hour practicals per week• Practicals are an essential part of the module and

are mandatory.

• 1 coursework task which includes 3 exercises will involve implementing a system in C++

Module Introduction

Scheduled learning and teaching activities

Contact hours

Lectures 12 hours

Practical classes/workshops 24 hours

Guided independent study Learning hours

Directed/independent study 42 hours

Preparation for assessments 72 hours

TOTAL: 150 hours

Module IntroductionWeek Topic

1 C and C++ basics

2 Functions Strings and Arrays

3 Pointers and Structured Data

4 Basics of C++ Object Orientation

5 Exercise 1 Demonstration and Feedback

6 Object Oriented Data Structures

7 Templates and STL

8 Libraries Building and Deployment

9 Streams

10 Exercise 2 Demonstration and Feedback

11 Revision

12 Coursework Demonstration and Submission

Textbooks and references

• Stroustrup, B, Programming: Principles and Practice Using C++; Addison-Wesley 2014.

• Meyers, S; Effective Modern C++, Addison-Wesley2014

• Stephen Prata; C++ Primer Plus (6th edition ), PearsonEducation 2012

• Stephen Prata; C Primer Plus (6th edition), PearsonEducation 2014

Learning outcomes

• Understand the fundamental concepts of C and C++ programming for object manipulation, data structuring and input/output control.

• Refine a problem specification into a collection of C++ classes.

• Create a software artefact specified in terms of C++ objects and their interrelations.

• Research the techniques for safe and efficient programming in C and C++.

Assessment

• 50% examination + 50% coursework

• Coursework • Week5 (01/11/2021-05/11/2021):Exercise 1 (20%) mandatory demonstration and formative verbal feedback

• Week10 (06/12/2021-10/12/2021):Exercise 2 (40%) mandatory demonstration and formative verbal feedback

• Week12 (20/12/2021-24/12/2021) :Demonstration and source code submission (40%), summative verbal feedback

C and C++ assessment

• Almost all C programs can be legally compiled as C++.

• However, if you are asked to write a program in C++ on this module you are expected to use C++’s features.

• If you don’t, you will lose marks even if your program works.

Software Developmentwith

C and C++

2021-2022 – Semester 1

Week 1 – C&C++ basics

History of C and C++

• First developed by Kernighan and Ritchie in 1972 as an alternative to assembler for writing the UNIX operating system.

• Standardized and developed throughout the 80s and 90s and still maintained today.

• C++ initially developed from C by Stroustrup in 1979 and evolved, both in time with C’s updates and independently, from there.

• C is currently the second most popular programming language; C++ is third.

The roles of C and C++

• C is important because it was developed explicitly as an alternative to assembler.

• This means it has the properties that:• The language and compiler add very little overhead to the

code.

• The code maps very closely to machine code.

• The additional run-time code made necessary by the language is relatively small.

• C++ generally shares these properties but reduces them somewhat because object orientation is intrinsically alien to machine code.

Uses of C and C++

• High performance: Because of their low overhead, C and C++ can often be more efficiently compiled than most other languages.

• Small systems: Systems with restricted amounts of memory or slower CPUs also benefit from reduced overhead in the language.

• Security: While writing secure code in C and C++ is difficult, knowing exactly what the computer is doing at any given time is often highly beneficial to security.

The good news

• You already know a lot of the syntax of C and C++.

• This is because most languages that came after it, such as Java, copied its syntax.

• FOR loops, IF statements, and WHILE loops are identical. Many other constructs are extremely similar.

The bad news

• Python and Java are both languages with a relatively large amount of overhead. They do a lot to hide the exact functions of the CPU, even when these are complex.

• In C++ and especially C this is no longer the case. You have to be fully aware of the complexity of operations that you might previously have considered simple.

• It may be helpful to revise earlier notes on low-level computer systems to put the material into context.

Tools for C and C++

• Because C and C++ were written in tandem with UNIX, the most standard tools are based on UNIX.

• The most standard compiler is gcc (Gnu C Compiler) which ships with most UNIX systems as standard. A new and popular alternative is clang which outputs very low-level VM code instead of machine code.

• Linux has gcc built-in. Mac OS X can install Xcodewhich includes clang. Beware that by default on Mac OS X, the command gcc actually runs clang!

C and C++ on Windows

• On Windows, you can run gcc or clang by installing Cygwin or MinGW. These simulate a UNIX environment just well enough for the tools to run.

• Microsoft has the cl compiler which comes as part of Visual Studio. It does not follow the C standards as closely as gcc, but does have some extra features to help programming for Windows.

• There are also third-party tools, some including compilers, for all platforms.

Tools for this module

• For this module we will use the Clion system.

• Clion is an IDE for C and C++ that manages compilation and also highlights code errors for you.

• Clion does not include its own compiler; it uses gcc or clang. Under Windows it uses these through Cygwin or MinGW.

• Although Visual Studio is available to use, we advise against using it because on later modules and in low-level development you may need to program using the UNIX standards.

A basic C program

#include <stdio.h>

int main() {

puts(“Hello World!\n”);

return 0;

}

A basic C program

#include <stdio.h>

int main() {

puts(“Hello World!\n”);

return 0;

}

#include in C resembles import in Java or Python,

except that the imported material is a header file;

what this means will be discussed later.

The angle brackets <> tell C to search for the stdio.h

file in the compiler’s standard libraries.

Using quotes “” is legal but tells C that the file should

be in the same directory.

A basic C program

int main() {

puts(“Hello World!\n”);

return 0;

}

C is not object oriented, and in C++ object

orientation is not mandatory as it is in Java.

You do not have to define classes (in C you cannot)

and your main “method” must not be in a class (and

is thus a function, not a method)

A basic C program

int main() {

puts(“Hello World!\n”);

return 0;

}

The syntax for defining a function is the same as a

method in Java but without the access specifier

(public/private .etc) since these don’t apply to

functions.

The MAIN function is the main program. It returns

an INT, which is returned to the operating system.

A basic C program

int main() {

puts(“Hello World!\n”);

return 0;

}

PUTS is the C function to output a string. (It’s part of stdio, that’s why we imported it.) “\n” at the end of the string represents the byte sent to the OS to tell it to move to the next line.

The same in C++

#include <iostream>

using std::cout;

using std::endl;

int main() {

cout << “Hello World!” << endl;

return 0;

}

C++ differences

• The .h can be left off the import. Traditionally built-in C++ libraries have no file extension.

• Instead of using the stdio library, we use the iostream library and stream output operators.

• These are a C++ addition that simplifies output but also makes the syntax more abstract.

• This is a good example of the difference in style between C and C++.

A simple loop

#include <stdio.h>

#include <stdint.h>

int main() {

for (uint8_t x=0; x<10; x++) {

printf(“%i\n”,x);

}

return 0;

}

Looking at the loop

for (uint8_t x=0; x<10; x++) {

printf(“%d\n”,x);

}

As mentoned before, the FOR syntax in C and C++ is identical to Java. (Java copied it from C++!)

The printf (print formatted) function is used to print out strings containing numbers or other material.

Also note the type declaration is unusual.

Type declarations in C

• In the original C, the types used were the same as in Java – int, float, etc.

• However, unlike Java, C compiles right down to machine code –and different computers have different abilities to handle numbers in machine code.

• This caused confusion with int meaning different things and having different properties based on the machine being compiled on. As a result, in 1999 the types were respecified to allow the programmer to specify exactly how the computer should store the number.

Integer standard typesType Memory Min Max

int8_t 1 byte -128 127

uint8_t 1 byte 0 255

int16_t 2 bytes -32768 32767

uint16_t 2 bytes 0 65535

int32_t 4 bytes -2147483648 2147483647

uint32_t 4 bytes 0 4294967295

int64_t 8 bytes -9223372036854775808 9223372036854775807

uint64_t 8 bytes 0 18446744073709551615

Integer standard types

• Modern processors can handle up to 32-bit numbers in single machine code instructions. Many can handle 64-bit numbers.

• However, smaller embedded systems may only be able to deal with 16-bit or even 8-bit numbers directly in their machine code.

• Managing larger numbers on these systems requires the compiler to include extra code to transfer carry, etc, information between parts of the number.

Relative types

• (U)Int_leastX_t declares the variable must have at least Xbits but may have more. This is used to allow for systems with machine code that may no longer handle smaller numbers.

• (U)Int_fastX_t declares the variable must have at least X bits and should be “fast” on the platform being used. The precise meaning of this is not defined but compilers are supposed to select a type native to the CPU’s code.

Printf

• In Python you would writeprint(“You have”,dogs,”dogs

and”,cats,”cats.”)

• In C you writeprintf(“You have %i dogs and %i

cats.\n”,dogs,cats);

• The first parameter (called the format string) gives the overall structure of what you want to print.

• You add “slots” into it with %i (or other markers we’ll see later), then fill them in.

The loop in C++

#include <iostream>

using namespace std;

int main() {

for (uint8_t x=0; x<10; x++) {

cout << +x << endl;

}

return 0;

}

The loop in C++

• Again, the code is mostly the same as in C except we are using the iostream facilities C++ provides. This is cleaner than printf:cout << “You have “ << dogs <<

“ dogs and “ << cats <<

“ cats.” << endl;

• However, note the + before x. This is because, without the specific information printf gives, C++ has to assume what format to use to print the contents of the variable. In the case of an 8-bit integer, by default, it assumes wrong! (It’s ok for larger integers though..)

Input

Int main() {

int32_t age;

puts(“How old are you?”);

scanf(“%i”,&age);

printf(“You typed %i.\n”,age);

if (age > 18) {

puts(“You can vote.”);

}

return 0;

}

Input in C• Scanf is the input equivalent of Printf.

• Normally modern programs do not use scanf because it is bad at handling errors (eg, if the user did not type a number). We will learn to do input better later. Use scanf for the moment.

• Note the & sign before age in scanf. This means that we are passing a pointer to age. This is necessary because we want scanf to change the value stored in variable age. We’ll go much more into pointers later on.

• We declare the variable as int32_t because this is what the%i specifier in scanf requires, even though it would be better to use a smaller type for an age.

Input in C++

Int main() {

uint16_t age;

cout << “How old are you?”;

cin >> age;

cout << “You typed” << age <<

endl;

if (age > 18) {

cout << “You can vote.”;

}

return 0;

}

Input in C

• Again at this stage, the code is similar except we use C++’s IO streaming functions.

• Cin >> is used for input. Again, this is not ideal at handling errors, although it is better than scanf. But use it for the moment.

• Note there is no & sign before age in the input statement. We still need the value of age to change, so we are still actually passing a pointer. But C++ deals with this for us in the background so we don’t need to add the explicit &.

• This can be helpful, but it can also be awkward, as learning the difference is vital to learning C and C++.

Conversion Specifiers in CConversion Output Specification

%a Floating-point number, hexadecimal(16进制) digits and p-notation

%c Single character..

%d Signed decimal integer.

%e Floating-point number, e-notation.

%f Floating-point number, decimal notation.

%i Signed decimal integer (same as %d ).

Conversion Specifiers in C

Conversion Output Specification

%o %o Unsigned octal integer.

%p A pointer.

%s Character string.

%u Unsigned decimal integer.

%x Unsigned hexadecimal integer, using hex digits 0 F.

%% Prints a percent sign

First exercise

• For your first practical exercise you will be writing some simple programs in C and C++ using syntaxes that should be familiar to you from other languages.

• From next week we will start to look in detail at the specifics of C and C++ and how they differ from the languages you already know.

Summary

• Basic knowledge about C and C++

• Basic form of C and C++ program

• Several different type of integer

• I/O of C & C++