Course List: http://www.c-jump.com/bcc/
Today:
What do we need to know at the very beginning
How to do simple computations
Things that make things safe or unsafe
objects: regions of memory
variables: access to objects
C++ types: size + behavior
declarations: type + name
Consider
x = y + 2;
x and y declared:
double x; int y = 7; x = y + 2;
Type determines operations
double x; // declaration of x int y = 7; // initialization of y x = y + 2; // addition and assignment
A statement that introduces a variable is called a declaration
A variable holds a value of a specified type
main.cpp is our source file
std_lib_facilities.h is the header for our course
#include "std_lib_facilities.h" int main() // C++ programs start by executing the function main { cout << "Hello, World!\n"; // output "Hello, World!" keep_window_open(); return 0; }
#include "std_lib_facilities.h" int main() // C++ programs start by executing the function main { cout << "Enter your name: "; string first_name; cin >> first_name; cout << "Your name is: " << first_name; keep_window_open(); return 0; }
Here, cin >> first_name; reads characters until a whitespace character is seen ("a word")
White space: space, tab, newline, and so on.
// Example: int main() { double x; // declaration of x int y = 7; // initialization of y x = y + 2; // addition and assignment string name = "Lisa"; return 0; }
// read first and second name: int main() { cout << "please enter your first and second names\n"; string first; string second; cin >> first >> second; // read two strings string name = first + ' ' + second; // concatenate strings // separated by a space cout << "Hello, "<< name << '\n'; }
// read name and age: int main() { cout << "please enter your first name and age\n"; string first_name; // string variable int age; // integer variable cin >> first_name >> age; // read cout << "Hello, " << first_name << " age " << age << '\n'; }
|
|
The type of a variable determines which operations are valid and what their meanings are for that type.
Name (identifier) consists of
letters ABC... abc...
digits 123...
underscores _
first character must be letter or underscore
distinct UPPERCASE and lowercase letters
no keywords: const, return, double, int, etc.
Again, name starts with a letter, contains letters, digits, and underscores.
Legal names Bad names ------------------- --------------- idx 12x number_of_elements time$to$market counter main line int if while double
Do not start names with underscores: _foo
those are reserved for C++ implementation and systems libraries
Choose meaningful names:
Meaningful names Bad names ------------------- ----------------------------------------- partial_sum mtbf, TLA, myw, nbv // confusing! element_count x, a, t // too short! text_chunk the_number_of_elements // too long! remaining_free_slots_in_the_symbol_table _EMPTY_STRING // starts with underscore
A very simple arithmetic:
int main() { // prompt for a number: cout << "please enter a floating-point number: "; double num; // floating-point variable cin >> num; cout << "num == " << num << "\nn+1 == " << num+1 // '\n' means "a newline" << "\nthree times num == " << 3*num << "\ntwice num == " << num+n << "\nnum squared == " << num*num << "\nhalf of num == " << num/2 << "\nsquare root of num == " << sqrt(num) // library function << endl // another name for newline ; }
A very simple arithmetic:
const double cm_per_inch = 2.54; // number of centimeters per inch int length = 1; // length in inches while (length != 0) // length == 0 is used to exit the loop { // a compound statement (a block) cout << "Please enter a length in inches: "; cin >> length; cout << length << "in. == " << cm_per_inch*length << "cm.\n"; }
bool: true or false
char: characters
int: integer numbers
float and double: floating-point (real) numbers
Note: fundamental types are aslo callled built-in types.
C++ programmers can define new types
Called user-defined types
We'll get to that eventually
The C++ standard library provides a set of types
string, vector, complex
Technically, these are user-defined types made using only facilities available to every user
All variables must be declared before they can be used in a program:
int counter; int month; int day; int year;
Note: C++ declarations end with a semicolon (;)
Declaration initializer is an optional part of the variable declaration.
Initializer provides initial value to our variables:
int counter = 1000; string s1 = "Hello, world"; string s2 = "1.2"; const double pi = 3.14;
Note: const transforms a variable into a constant value...
...once initialized, const variable cannot change again.
Declaration initializer is the only way to set value of a const variable.
int main() { const char LF = '\n'; // a new line character bool FLAG_BUSY = false; string social_security_number; double form1040a_field_33; bool FLAG_BUSY = true; // *** Error! Variable already declared bool flag_busy = false; // OK, but *extremely* bad style double 1040a_total; // *** Syntax error: first character must // be letter or underscore return 0; }
An object is some memory that can hold a value of a given type
A variable is a named object
A declaration names an object
|
|
Language rule: type safety
Every object will be used only according to its type
A variable will be used only after it has been initialized
Only operations defined for the variable's declared type will be applied
Every operation defined for a variable leaves the variable with a valid value
Ideal: static type safety
A program that violates type safety will not compile
The compiler reports every violation (in an ideal system)
Ideal: dynamic type safety
If you write a program that violates type safety it will be detected at run time
Some code (typically "the run-time system") detects every violation not found by the compiler (in an ideal system)
Type safety is a very big deal
Try very hard not to violate it
When you program, the compiler is your best friend...
...but it won't feel like that when it rejects code you're sure is correct
C++ is not (completely) statically type safe
No widely-used language is (completely) statically type safe
Being completely statically type safe may interfere with your ability to express ideas
C++ is not (completely) dynamically type safe
Many languages are dynamically type safe
Being completely dynamically type safe may interfere with the ability to express ideas and often makes generated code bigger and/or slower
Almost all of what you'll be taught here is type safe
We'll specifically mention anything that is not
// changing the value of a variable int a = 7; // a variable of type int called a // initialized to the integer value 7 a = 9; // assignment: now change a's value to 9 a = a + a; // assignment: now double a's value a += 2; // increment a's value by 2 ++a; // increment a's value (by 1)
C++ built-in types map directly to computer main memory
A char is stored in a memory byte
An int is stored in a memory word (32 or 64 bit)
A double fits in a floating-point register (64 bit)
C++ built-in operations map directly to machine instructions
An integer + is implemented by an integer add operation
An integer = is implemented by a simple copy operation
C++ provides direct access to most of the facilities provided by modern hardware
// Beware: C++ does not prevent you from trying // to put a large value into a small variable // (though a compiler may warn) int main() { int a = 20000; char c = a; int b = c; if ( a != b ) { // != means "not equal" cout << "oops!: " << a << "!=" << b << '\n'; } else { cout << "Wow! We have large characters\n"; } }
Try this example to see what value b gets on your machine
// Beware: C++ does not prevent you from trying to use a variable // before you have initialized it (though a compiler typically warns) int main() { int x; // x gets a "random" initial value char c; // c gets a "random" initial value double d; // d gets a "random" initial value // not every bit pattern is a valid floating-point value double dd = d; // potential error: some implementations // can't copy invalid floating-point values cout << " x: " << x << " c: " << c << " d: " << d << '\n'; }
Always initialize your variables!
This handout is using material from Programming -- Principles and Practice Using C++
About the author: Bjarne Stroustrup's homepage