CS246-F20-03-IntroToC++
3. Basics of C++
CS246 Fall 2020
Prof. Mike Godfrey
University of Waterloo
Lecture 3.1
• Quick intro to C++ basics
– Variables and constants
– Simple types
CS246
// Your first C++ program!
#include
#include
using namespace std; // Saves some typing, but beware
const string kidDrink = “juice”; // global variables
string adultDrink = “coffee”;
int main (int argc, char* argv[]) {
int age = 100;
while (age > 0) {
cout << "How old are you? ";
cin >> age;
cout << "Would you like some ";
if (age < 18) {
cout << kidDrink << "?" << endl;
} else {
cout << adultDrink << "?" << endl;
}
if (age == 56) {
adultDrink = "beer"; // change global var!
}
}
}
• As in ANSI C, C++ support real named constants
i.e., not #DEFINE constant macros, like in the old days of C
• Variables can be declared anywhere a stmt can be
• Can declare a loop counter to exist only inside the loop:
Variables and constants
int numSheep;
cin >> numSheep;
const int numLegs = 4 * numSheep;
for (int i = 0; i < numLegs ; i++) {
// do stuff
}
// i isn't visible after the loop
// (that's a good thing!)
• C++ has a bool type, with special values true and false
• Choose good names to improve code readability:
– Good names: doneProcessing, isStale, errorFound
– Weak names: processingStatus, onOrOff
– Terrible names: flag, status, condition2
Booleans
bool doneProcessing = false;
while (!doneProcessing) {
…
if (someCondition) {
doneProcessing = true;
}
}
const bool altTrue = false;
Booleans
• C/C++ let you treat arithmetic (including char) and pointer
values are having true/false meaning …
– Zero (NULL ptr) means false
– Non-zero (non-NULL ptr) means true
• But we recommend you don't use this! (It's even illegal in Java!)
– Consider these:
if (!p) // where p is a ptr
if (!n)
if (n = 0)
if (n == 0) // same as !n
if (0 == n)
if (nullptr != p) // Better!
if (0 = n)
#include
#include
using namespace std;
// int vs. unsigned int
int main (int argc, char* argv[]){
unsigned int ui = 5;
for (int i=0; i<10; i++) { cout << "ui = " << ui << endl; ui--; } } ui = 5 ui = 4 ui = 3 ui = 2 ui = 1 ui = 0 ui = 4294967295 ** ui = 4294967294 ui = 4294967293 ui = 4294967292 The variable ui is a 32-bit int in the range: 0 ... 4,294,967,295 The variable i is a 32-bit int in the range: −2,147,483,648 ... 2,147,483,647 ** Note that you can't rely on what value ui will have after subtracting 1 from zero, it just won't be -1. End CS246