C++ Crash Course Class 2 ssh, memory, data types, variables.

38
C++ Crash Course Class 2 ssh, memory, data types, variables

Transcript of C++ Crash Course Class 2 ssh, memory, data types, variables.

Page 1: C++ Crash Course Class 2 ssh, memory, data types, variables.

C++ Crash Course

Class 2ssh, memory, data types, variables

Page 2: C++ Crash Course Class 2 ssh, memory, data types, variables.

Agenda

• Learn to use SSH and compile code on the undergrad lab accounts

• Learn how to code the C++ way

Page 3: C++ Crash Course Class 2 ssh, memory, data types, variables.

Variables and Basic Types

• C++ is a typed language– each variable has a specific data type which does

not change through the course of the program– Type specifies the format the data is stored in,

and how much space it takes up– Types say what data means and what operations

can be performed on it• Made up of primitive types (char, int, float) as

well as our own types – compound types, variable-length types

Page 4: C++ Crash Course Class 2 ssh, memory, data types, variables.

Primitive TypesType Meaning Min Size

bool boolean NA

char character 8 bits

wchar_t Wide character 16 bits

short Short integer 16 bits

int integer 16 bits

long Long integer 32 bits

float Single-precision floating point

6 significant digits

double Double-precision floating point

10 significant digits

Long double Extended-precision floating point

10 significant digits

To avoid mysterious bugs, most programmers typically use int, char, and double as defaults unless there’s a good reason not to. Know these exist though!

Page 5: C++ Crash Course Class 2 ssh, memory, data types, variables.

Computer Memory: Basics

• The data in memory is just a series of 0’s and 1’s, each of which is called a bit

• No inherent structure• We divide it up:– 1 bit: 1 or 0– 1 byte: 8 bits– 1 word: 4 bytes

• Each byte of memory has an address• Data type tells us how to interpret the bytes

at a certain address in memory

Page 6: C++ Crash Course Class 2 ssh, memory, data types, variables.

Binary values

• Binary is a number in base 2• Types are limited in how large they can get by

their size• Since an int is 16 bits long, it can represent 216

unique numbers

Page 7: C++ Crash Course Class 2 ssh, memory, data types, variables.

Integral Types

• Integers, characters, boolean values are the integral types– as opposed to the floating-point data types

• char is big enough for the basic character sets; wchar_t is needed for extended character sets (such as Chinese / Japanese)

Page 8: C++ Crash Course Class 2 ssh, memory, data types, variables.

Signed and unsigned

• signed types can be either positive or negative• unsigned types represent only positive

numbers (including 0)• int, short and long are all signed by default• unsigned types have the first digit of the type

represent whether it is positive or negative– 1 means negative– 0 means positive or 0

Page 9: C++ Crash Course Class 2 ssh, memory, data types, variables.

Signed and unsigned

• C++ will still allow you to assign a negative number to an unsigned type

• Result is negative value mode type size

Page 10: C++ Crash Course Class 2 ssh, memory, data types, variables.

Floating-point Types• float, double and long-double are all floating

point values• floats are usually in one word (32 bits); doubles

in two words (64 bits); long double in 3 or 4 words (96 or 128 bits)

• Size of the type determines the number of possible significant digits

• Most real-world programs require a double level of precision over a float

Page 11: C++ Crash Course Class 2 ssh, memory, data types, variables.

Literal Constants

• Hard-coded into the program• 42, 3.14159, ‘b’ are all literal constants• These exist only for the built-in types, not

library types• Literals have an associated type– 42 is an int– 3.14159 is a float– ‘b’ is a char

Page 12: C++ Crash Course Class 2 ssh, memory, data types, variables.

Integer literals

• Can write a literal integer in many notations• C++ supports decimal (base 10), octal (base 8) or

hexadecimal (base 16)– 20 for decimal– 024 for octal (preface with a 0)– 0x14 for hexadecimal (preface with a 0x)

• Conversion trick:– splitting a binary number into groups of three will give

you its octal representation– splitting into groups of four will give you its hex

representation

Page 13: C++ Crash Course Class 2 ssh, memory, data types, variables.

Boolean literals

• true and false are literals of type bool

Page 14: C++ Crash Course Class 2 ssh, memory, data types, variables.

Escape Sequences

• Last time we talked about \n, the newline character

• Several others:

newline \n horizontal tab \t

vertical tab \v backspace \b

carriage return \r formfeed \f

alert (bell) \a backslash \\

question mark \? single quote \’

double quote \”

Page 15: C++ Crash Course Class 2 ssh, memory, data types, variables.

Character String Literals

• “Hello World!”• internally looks like:

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘ ‘ ‘W’ ‘o’ ‘r’ ‘l’ ‘d’ ‘!’ ‘\0’

The \0 is the null character, used to say that we’ve reached the end of a string.

Page 16: C++ Crash Course Class 2 ssh, memory, data types, variables.

Variables

• Variables provide storage space of a specific type

• Seemingly straightforward, but…

• Expressions:– lvalue: an lvalue may be either the left-hand or right-hand

side of an assignment– rvalue: an rvalue expression may appear on the right hand

side, but not the left hand side, of an assignment

Page 17: C++ Crash Course Class 2 ssh, memory, data types, variables.

Variables• Variables are lvalues; numeric literals are rvalues

Given:int units_sold = 0;double sales_price = 0, total_revenue = 0;

You cannot say the following:units_sold * sales_price = total_revenue;

or0 = 1;

Page 18: C++ Crash Course Class 2 ssh, memory, data types, variables.

Variable Naming

• The name of a variable is its identifier– int somename, someName, SomeName,

SOMENAME;– All the above are different, since identifiers are

case-sensitive– In C++, must begin with a letter or an underscore– Must be composed of letters, digits, and the

underscore character– No length restrictions – easier to program if it’s

shorter though

Page 19: C++ Crash Course Class 2 ssh, memory, data types, variables.

Reserved Words• These can’t be used as identifiers:asm do if return

auto double inline short

bool dynamic_cast int signed

break else long sizeof

case enum mutable static

catch explicit namespace static_cast

char export new struct

class extern operator switch

const false private template

const_cast float protected this

continue for public throw

default friend register true

delete goto reinterpret_cast

Page 20: C++ Crash Course Class 2 ssh, memory, data types, variables.

Conventions

• Variables are usually only in lowercase• Identifiers give some indication of its use – if

at all possible, avoid creating “int x, y, z”• Identifiers with multiple words have

underscores between them or have each subsequent word capitalized

Page 21: C++ Crash Course Class 2 ssh, memory, data types, variables.

Defining objects

int units_sold;double sales_price, avg_price;std::string title;Sales_item curr_book;

Starts with a type specifier, with a comma-separated list of names

Multiple variables can be defined in a statement

Page 22: C++ Crash Course Class 2 ssh, memory, data types, variables.

Initialization• A definition specifies type and identifier, and can

also provide an initial value, which initializes the object

• There are two ways to initialize:– copy-initialization:

• int ival = 1024;– direct-initialization:

• int ival(1024);• This is different from assignment, unlike in other

languages – we’ll get into that much later

Page 23: C++ Crash Course Class 2 ssh, memory, data types, variables.

Always initialize your variables!

• Though the compiler may not notice, if you don’t initialize your variables, you’ll get a runtime issue

• If you don’t initialize a variable, then there’s still a value – whatever was in the memory block now occupied by the variable is still there, and now being interpreted as this new type

Page 24: C++ Crash Course Class 2 ssh, memory, data types, variables.

Definitions and Declarations• defining a variable allocates space, and may

make an initial value• declaring a variable makes it known to the

program– definitions are declarations; declarations are not

necessarily definitions

The keyword extern makes the variable available without allocating storage – declares but does not defineUsed when you know the variable is defined elsewhere – a variable must be defined exactly once

Page 25: C++ Crash Course Class 2 ssh, memory, data types, variables.

Scope

• Scope is nearly always determined by curly brackets {}

• If you declare a variable inside a function, then you won’t be able to access it outside of the function

• Similarly, if you declare a variable inside a loop, you won’t be able to access it in the rest of the function in which it appears

Page 26: C++ Crash Course Class 2 ssh, memory, data types, variables.

Using const• In real-world programming, you’re often going to need

to compare to specific values• Three number average program: 70 was used, but to

someone looking at it later, the reason is unclear• Thus we have const: we can create a variable that will

never change after its initialization

• const int pass_cutoff = 70;

Trying to modify pass_cutoff will result in a compile-time error

Page 27: C++ Crash Course Class 2 ssh, memory, data types, variables.

References• Alternative name for an object• A reference is a compound type

– defined in terms of another type

int ival = 1024;int &refVal = ival;

refVal now refers to ival

so:

refVal += 2; // adds 2 to ival

int ii = refVal;

…results in ii having the value currently in ival

Page 28: C++ Crash Course Class 2 ssh, memory, data types, variables.

References• A reference is effectively an alias for a variable

• References cannot be rebound to a different object

• We can define as many as we like:

int i = 1024, i2 = 2048;int &r = I, r2 = i2;int i3 = 1024, &ri = i3;int &r3 = i3, &r4 = i2;

Page 29: C++ Crash Course Class 2 ssh, memory, data types, variables.

References• A reference is effectively an alias for a variable

• References cannot be rebound to a different object

• We can define as many as we like:

int i = 1024, i2 = 2048;int &r = I, r2 = i2;int i3 = 1024, &ri = i3;int &r3 = i3, &r4 = i2;

What just happened to the variables?

Page 30: C++ Crash Course Class 2 ssh, memory, data types, variables.

References• A reference is effectively an alias for a variable

• References cannot be rebound to a different object

• We can define as many as we like:

int i = 1024, i2 = 2048; // i: 1024, i2: 2048int &r = I, r2 = i2;int i3 = 1024, &ri = i3;int &r3 = i3, &r4 = i2;

What just happened to the variables?

Page 31: C++ Crash Course Class 2 ssh, memory, data types, variables.

References• A reference is effectively an alias for a variable

• References cannot be rebound to a different object

• We can define as many as we like:

int i = 1024, i2 = 2048; // i: 1024, i2: 2048int &r = i, r2 = i2; // r: 1024, r2: 2048int i3 = 1024, &ri = i3;int &r3 = i3, &r4 = i2;

What just happened to the variables?

Page 32: C++ Crash Course Class 2 ssh, memory, data types, variables.

References• A reference is effectively an alias for a variable

• References cannot be rebound to a different object

• We can define as many as we like:

int i = 1024, i2 = 2048; // i: 1024, i2: 2048int &r = i, r2 = i2; // r: 1024, r2: 2048int i3 = 1024, &ri = i3; // i3: 1024, ri: 1024int &r3 = i3, &r4 = i2; // r3: 1024, r4: 2048

What just happened to the variables?

Page 33: C++ Crash Course Class 2 ssh, memory, data types, variables.

What does this code do?

int i, &ri = i;i = 5; ri = 10;std::cout << i << “ “ << ri << std::endl;

Page 34: C++ Crash Course Class 2 ssh, memory, data types, variables.

What does this code do?

int i, &ri = i;i = 5; ri = 10;std::cout << i << “ “ << ri << std::endl;

10 10

Page 35: C++ Crash Course Class 2 ssh, memory, data types, variables.

typedef names• We can make synonyms for types, in order to make the types more

meaningful

typedef double wages;typedef int exam_score;typedef wages salary;

Now we have three new types: wages, exam_score, salary

wages hourly, weekly;exam_score test_result;

hourly and weekly are now doubles; test_result is an int

Page 36: C++ Crash Course Class 2 ssh, memory, data types, variables.

typedefs

• …Hide the implementation of a given type and emphasize the purpose instead

• …streamline complex type definitions to make them easier to understand

• …allow a single type to be used for more than one purpose while making the purpose clear each time the type is used

Page 37: C++ Crash Course Class 2 ssh, memory, data types, variables.

Enumerations

• Could create several const variables when trying to track program states

– e.g.:

const int input = 0;const int output = 1;const int append = 2;

Page 38: C++ Crash Course Class 2 ssh, memory, data types, variables.

Enumerations• This can be more quickly and easily expressed with an enum

enum open_modes {input, output, append};

…which allows us to say:

open_modes var = input;

Each enum defines a unique type.

You cannot assign 0, 1, or 2 to an open_modes object, even though the underlying representation of input, output and append are as ints