Professional Documents
Culture Documents
Variables
The syntax for declaring a variable is:
data_type variable_name ;
or, for several variables of the same type:
Readability
Pick meaningful variable names that describe
Basic types
int for signed integers (4 bytes*)
range: -231..+231
range: 0..+232
range: 0-1
Literals
#include<iostream>
using namespace std;
int main () {
integer literal
cout << 10
<< "USD = "
<< 8.2
double literal
<< "EUR\n";
return 0;
string literals
}
Literals
Major disadvantages:
a literal cannot be reused (you have to type it in
every time)
it is easy to make a typo
if you want to change it, you have to make sure you
change all of its occurrences inside the program.
Good idea:
Use #define (C++ preprocessor directive) to define
Look ma, no semicolon!
#define NUM_DOLLARS
10
a literal
#include<iostream>
using namespace std;
int main () {
cout << NUM_DOLLARS;
return 0;
}
#defined constants
Location: with other directives (e.g. #include)
Syntax: #define
UNIQUE_NAME
some_value
Before compiling, pre-processor does 'find &
named constants
Declared like variables BUT
preceded with the keyword const
initialized at declaration
their value CANNOT change afterwards.
#include<iostream>
using namespace std;
int main () {
const int num_dollars = 10;
cout << num_dollars;
// num_dollars = 20; ILLEGAL!
return 0;
}
8
Operators
Assignment operator:
=
Arithmetic operators: +, , *, /, %
Relational operators: <, >, <=, >=, ==, !=
Logical operators: &&, ||, !
Operators
()
! Unary
higher precedence
* / %
+
< <= >= >
==
!=
&&
||
=
lower precedence
10