[C++] Chap 01 - C++ Basics
[C++] Chap 01 - C++ Basics
Variables
- Identifiers :
- starts with letter or underscore(_), the rest characters must be letters, digits, underscore.
- Case-sensitive
- Variables
- A memory location to store data for a program
- Must declare first
- Escape Sequences
- “Extend” the character set
- Uses Backslash (
\)
Assignment rules / Compatibility
1
2
3
int variable;
intvariable = 2.99;
// Type mismatch, but only integer part is stored.
- Some special cases are allowed
1
2
double doublevar;
doublevar = 2;
- Literals : considered “constants” (cannot be changed)
- E.g) 2, 5.75, ‘Z’, “Hello World”
Arithmetic Precision
- “Highest-order operand” determines type of arithmetic “precision” performed
1
2
double x = 1/2/3.0/4;
// Calculations are done "one-by-one" 1/2=0, 0/3.0=0.0, 0.0/4=0.0
Type casting
- Implicit (Automatic Type casting)
- 17/5.5 → cast 17 to 17.0 ( “double” precision division is performed)
- Explicit type casting
- (double)17/5.5
1
2
3
4
5
double a;
a=((double)9/5);
a=(9/(double)5);
a=(double)(9/5); // X
a=(9.0/5);
Increment, Decrement Operators
- Post / Pre Increment / Decrement
- Postfix : RValue, Increase value after line
- Prefix : Lvalue, Increase before execution
Console Input/Output
cin,cout,cerr- Must have the following lines :
1
2
#include <iostream>
using namespace std;
- cout
- New lines in output : ‘\n’ or
<<endl - Cascading is allowed :
<<a << b
- New lines in output : ‘\n’ or
- cin
- Extraction Operator
>> - Must input “to a variable”
- Extraction Operator
- Cout Formatting
1
2
3
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2); // shows two digits under decimal point
Comment
//or/* */
Libraries
- C++ standard libraries :
#include <LIBRARY_NAME>
Namespaces
- Collection of name definitions
using namespace std;
This post is licensed under CC BY 4.0 by the author.