slides

advertisement
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
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
Primitive Types
Type
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 10 significant digits
point
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!
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
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
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)
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
Signed and unsigned
• C++ will still allow you to assign a negative
number to an unsigned type
• Result is negative value mode type size
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
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
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
Boolean literals
• true and false are literals of type bool
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
\”
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.
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
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;
or
0 = 1;
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
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
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
Defining objects
int units_sold;
double sales_price, avg_price;
std::string title;
Sales_item curr_book;
Starts with a type specifier, with a commaseparated list of names
Multiple variables can be defined in a statement
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
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
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
define
Used when you know the variable is defined
elsewhere – a variable must be defined exactly once
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
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 compiletime error
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
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;
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?
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: 2048
int &r = I, r2 = i2;
int i3 = 1024, &ri = i3;
int &r3 = i3, &r4 = i2;
What just happened to the 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: 2048
int &r = i, r2 = i2;
// r: 1024, r2: 2048
int i3 = 1024, &ri = i3;
int &r3 = i3, &r4 = i2;
What just happened to the 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;
// i: 1024, i2: 2048
// r: 1024, r2: 2048
// i3: 1024, ri: 1024
// r3: 1024, r4: 2048
What just happened to the variables?
What does this code do?
int i, &ri = i;
i = 5; ri = 10;
std::cout << i << “ “ << ri << std::endl;
What does this code do?
int i, &ri = i;
i = 5; ri = 10;
std::cout << i << “ “ << ri << std::endl;
10 10
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
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
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;
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
Download