Programming C++ Types

Preview:

Citation preview

1

Programming C++

Types

Michał BeretaCracow University of Technology

http://torus.uck.pk.edu.pl/~beretam/beretam@torus.uck.pk.edu.pl

2

TypesEach variable has to be declared before it can be

used.

This allows the compiler to decide how to proceed with this variable during execution of the

program.

For example:

x + y

There is differences how to perform addition for int variables or for floats or other types.

3

Types

C++ is statically typed language.

It means that programmer has to define a type of each variable in the program.

Once specified, the type of a given variable cannot be changed.

4

Python

Python is dynamically typed language.

For example:

x = 3.14print xx = 'Hello World!'print x

This is not possible in C++.

5

TypesThis is not possible in C++.

For example:float x = 3.14f;cout << x <<endl;

x = "Hello World!";cout << x <<endl;

ERROR!!!

6

TypesThis is not possible in C++.

For example:float x = 3.14f;cout << x <<endl;

string x = "Hello World!";cout << x <<endl;

ERROR!!!

7

Types

Categorization, version 1:

●Fundamental types●Derivative types

8

Types

Categorization, version 2:

●Build-in types●User-defined types

9

short int x1;

int x2;

long x3;

long int x4;

long long x5;

cout << "sizeof(x1)=" << sizeof(x1) << endl;

cout << "sizeof(x2)=" << sizeof(x2) << endl;

cout << "sizeof(x3)=" << sizeof(x3) << endl;

cout << "sizeof(x4)=" << sizeof(x4) << endl;

cout << "sizeof(x5)=" << sizeof(x5) << endl;

10

cout << "sizeof( short )=" << sizeof( short ) << endl;cout << "sizeof( int )=" << sizeof( int ) << endl;cout << "sizeof( long )=" << sizeof( long ) << endl;cout << "sizeof( long long )=" << sizeof( long long ) << endl;

11

Types

For characters:cout << "sizeof( char )=" << sizeof( char ) << endl;

12

TypesAll of the above mentioned types can be

defined as signed or as unsigned.

Signed – one bit is for remembering the sign of the value stored in the variable.

Unsigned – all bits remember the value that is non-negative.

13

Typesnp.

signed char c; → [-128; 127]

unsigned char c; → [0, 255]

14

TypesThe default for

int x;

is

signed int x;

15

TypesThe default for

char x;

is not specified and depends on the compiler!

signed char x; or unsigned char x;??

16

TypesFor floating-point variables there are:

float x1;double x2;long double x3;

You cannot use unsigned keyword with the above types!(Probably there will be no error, but the keyword

unsigned will be ignored.)

17

Typescout << "sizeof( float )=" << sizeof( float ) << endl;cout << "sizeof( double )=" << sizeof( double ) << endl;cout << "sizeof( long double )=" << sizeof( long double ) << endl;

18

TypesHaving different types we can decide and choose

between the speed of the execution of the program and the accuracy.

19

TypesIn C++ you can define new variables in any place

you need ( on flight definition ) - variables do not have to be defined before the instructions as in some other languages.

For example:int x = 3;int y = 4;x = 3 * y + x;int z = x + y;cout << z ;

Some variables

Some computations

A new variable in the place where it is needed.

20

TypesLiterals (constants):Invariant program elements are called "literals" or

"constantsIntegers:17, 33, -56, etc.

If we start with 0, the integer is in the octal numeral system

For example:010014

21

TypesIntegers:

If we start with 0x, the integer is in the hexadecimal numeral system

For example:0x100x14

In hexadecimal system we use difits 0-9 anf letters A-F (or a-f );

22

TypesWe can specify, whether the value is unsigned by

adding u and/or for example long instead of int (which is the default), by appending L

(or l ):

132132u132L ( or 132l )132uL

23

TypesFloating point literals:

12.38e2 = 8 * pow(10,2) = 8005.2e-3 = 5.2 * pow(10,-3) = 0.0052

24

Types'a' - letter a'7' - digit 7 (not the value of 7 !!!)

char c;c = 'a';cout << c <<endl;cout << (int)c <<endl;

c = '7';cout << c <<endl;cout << (int)c <<endl;

25

TypesSpecial:\b - backspace\f - form feed (new page)\n - new line\r - carriage return\t - tabulator\v - vertical tabulator\a - alarm

26

TypesSpecial:'\'' - 'for example:char c = ''; //ERROR!char c = '\'' ; // CORRECT!

'\\' - backslash '\”\'\0' - NULL'\?'

27

Types'a' is the same as 97, 0141 in octal, or 0x61 in

hexadecimal (ASCII code).char c;c = 'a';cout << c <<endl;c = 97;cout << c <<endl;c = 0141;cout << c <<endl;c = 0x61;cout << c <<endl;

28

Strings● Strings are arrays of characters with the

NULL at the end.● The real memory reserved can be bigger

than that indicated by NULL ( '\0' ).

29

Stringschar t[] = "Hello!";cout<< "length=" << strlen( t ) << endl;

char t2[7];t2[0] = 'H';t2[1] = 'e';t2[2] = 'l';t2[3] = 'l';t2[4] = 'o';t2[5] = '!';t2[6] = '\0';cout<< "length=" << strlen( t2 ) << endl;

There has to be NULL at the end of each string!!!

30

Stringschar t[20] = "Hello!";cout<< "length=" << strlen( t ) << endl;

31

Stringschar t[20] = "Hello!";t[3] = '\0';cout<< t <<endl;cout<< "length=" << strlen( t ) << endl;

32

Stringschar t[20] = "Hello!";t[6] = 'a';cout<< t <<endl;cout<< "length=" << strlen( t ) << endl;

Danger!Where is the NULL sign? Where is the end f the string?

33

StringsRemember!You cannot break strings!

“This isa string”; //Error!

But:“This is”“a string”; //Correct! These two lines will be concatenated into

just one string!

34

Strings#include <string>using namespace std;

string is not a simple array. This is a new class.

string s = "Hello!";cout << s << endl;

s is an object of class string !

35

Numerical LimitsC version

#include <climits> or#include <limits.h>

#include <cfloat> or#include <float.h>

36

Numerical Limitscout<< "INT_MAX: " << INT_MAX << endl;cout<< "RAND_MAX: " << RAND_MAX << endl;cout<< "FLT_MIN: " << FLT_MIN << endl;cout<< "DBL_MAX: " << DBL_MAX << endl;

37

Numerical LimitsC++ version

#include <limits>

using namespace std;

38

Numerical Limits //print maximum of integral types

cout << "max(short): " << numeric_limits<short>::max() << endl;

cout << "max(int): " << numeric_limits<int>::max() << endl;

cout << "max(long): " << numeric_limits<long>::max() << endl;

cout << endl;

//print maximum of floating-point types

cout << "max(float): " << numeric_limits<float>::max() << endl;

cout << "max(double): " << numeric_limits<double>::max() << endl;

cout << "max(long double): " << numeric_limits<long double>::max() << endl;

cout << endl;

//print whether char is signed

cout << "is_signed(char): " << numeric_limits<char>::is_signed << endl;

cout << endl;

39

Numerical Limits

40

Derivative Types● Derivative types are based on

fundamental types.● Example: Array of ints is a derivative

type of type int● Example: Pointer to a variable of type int

is derivative type of type intint myArray[10];int *myPointer;

41

Derivative Types● Operators used for creating derivative

types:– [] - array– * - pointer– () - function returning a variable of a given

type – & - reference to a variable of a given type

42

Derivative TypesPointer holds a address in the memory of a

given variable.

int x = 10;int *px;px = &x;

cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of x cout<< px << endl; //writes the value of the address

43

Derivative Typesint x = 10;int *px;px = &x;int z = *px; // the same as z = x;

cout<< x << endl; //writes value of xcout<< z << endl; //writes value of z z = 20;cout<< x << endl; //writes value of xcout<< z << endl; //writes value of z

44

Derivative Typesint x = 10;int *px;px = &x;

cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of xx = 20;cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of x

45

Derivative Typesint x = 10;int *px;px = &x;

cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of x*px = 30;cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of x

46

Derivative Typesint x = 10;int *px;px = &x;cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of xpx = 30; //ERROR!!!cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of x

47

Derivative Typesint x = 10;int *px;px = &x;

cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of xpx = (int *)30; //ERROR!!!cout<< x << endl; //writes value of xcout<< *px << endl; //writes value of x

48

Derivative Typesint *px; // not initialized! Random value!cout<< px <<endl;

In Debug mode

49

Derivative Typesint x = 10;int & rx; //ERROR!! Reference must be initialized!

cout<< rx <<endl;

50

Derivative Typesint x = 10;int &rx = x;

cout<< rx <<endl;rx = 20;cout<< rx <<endl;cout<< x <<endl;

51

Derivative TypesReference is like another name for the the same variable.

Pointer is an address of the variable in the memory.

Reference cannot refer to “nothing”.

Pointer can point to “nowhere” ( it means, it can point to a random place in the memory, where no variable exists ).

52

Derivative Typesvoid type

void *p; // p points to an object of an unknown type

void function(); // function does not return any value

53

Derivative TypesHow long does the variable live?

How long is the variable avaiable? (scope of the variable)

54

Derivative TypesLocal scope

{//...int x; //local scope//...

}//x is here unknown

55

Derivative Typesfunction scope

void function(){

//...int x; //function scope//...

}//x is here unknown

56

Derivative TypesFile scope

int global_x = 100; int main(){

//...}Variable global_x is known in the whole file from the place

where it is defined.It is global, yet to be known in other files it has to be

declared:extern int global_x;

57

Derivative TypesClass scope – variable known inside the class.

58

Derivative TypesShadowing – one variable shadows another with the same

name

int x = 10;int main(){

cout<< "in main: "<< x << endl;{

int x = 20; //shadowingcout<< "local: "<< x << endl;

}cout<< "in main 2: "<< x << endl;return 0;

}

59

Derivative TypesShadowing

int x = 10;int main(){

cout<< "in main: "<< x << endl;{

int x = 20; //shadowingcout<< "local: "<< x << endl;cout<< "local 2: "<< ::x << endl;

}cout<< "in main 2: "<< x << endl;return 0;

}

60

Modifiersconst – creates constant variable – the value of suc ha variable

cannot change

const float pi = 3.14; //initialization – OK!

pi = 222; //assigning new value – ERROR!

Initialization – assining a value in the momoment of “birth”

61

Modifiersconst vs #define

#define PI 3.14

const float pi = 3.14;

PI is not really a variable. It is a string which will be put in each place where PI exists in your code.

62

Modifiers#define PI 3.14

● Compiler cannot check the validity of the scope ( as PI is not a variable)

● No type check control● No possibility to use pointer or reference to PI● You cannot use a debugger with PI!

63

Modifiersregister int x;

We suggest the complier that x should be in the registry for a very fast access.

Compiler can ignore this modifier.

64

Modifiersvolatile int x;

The value of x can change very rapidly so the compiler should not optimize the acces to this variable and should check the true value every time the variable is used ( the compiler should check in the memory, not in the registry).

x can be changed from outside of the program, by another program wchich shares a memory with our program.

65

Modifierstypedef – defines a new name for a given type

typedef int price;

price x = 12;price z = x / 23;price v[10];

66

Modifierstypedef – defines a new name for a given type

typedef float price;typedef int * pointer;price x = 12;price z = x / 23;price v[10];pointer px; // the same as: int *x;Very usefull when we want to change the types of several

variable at once.typedef does not create a new type! It is just a new name for

an existing type.

67

Enumerative typeenum – creates an enumerative type ; a new type for integer

types

enum action { start, pause, resume, end };action a = start;action b = pause;action c = resume;action d = end;cout<< a << endl; cout<< b << endl; cout<< c << endl; cout<< d << endl;

68

Enumerative typeenum – creates an enumerative type ; a new type for integer

types

enum action { start = 10 , pause, resume, end };action a = start;action b = pause;action c = resume;action d = end;cout<< a << endl; cout<< b << endl; cout<< c << endl; cout<< d << endl;

69

Enumerative typeenum – creates an enumerative type ; a new type for integer

types

enum action { start , pause, resume = 15, end };action a = start;action b = pause;action c = resume;action d = end;cout<< a << endl; cout<< b << endl; cout<< c << endl; cout<< d << endl;

70

Enumerative typeenum – creates an enumerative type ; a new type for integer

types

enum action { start = 20, pause, resume = 7, end };action a = start;action b = pause;action c = resume;action d = end;cout<< a << endl; cout<< b << endl; cout<< c << endl; cout<< d << endl;

71

Enumerative typeenum action { start = 20, pause = 19, resume, end };action a = start;action b = pause;action c = resume;action d = end;cout<< a << endl; cout<< b << endl; cout<< c << endl; cout<< d << endl;

if( start == resume )

cout<< "yes"<< endl;else

cout<< "no"<< endl;

72

Enumerative typeEnums are very usefull when passing options as

parameters to the functions. It allows to control the function parameters already

during compilation. For example, if the function expects a parameter of type “action” it will not accept any “int” as parameter, although enums are also integers.

73

Enumerative typeenum action { start = 20, pause = 19, resume, end };

void function( action a ){

//...}

int main(){

function( start ); // OK !function( 20 ); //ERROR!

}

Recommended