C++ basic syntax SPU
C++ basic syntax SPU
69
Basic C++ Syntax
Overview
70
Basic C++ Syntax
Look at these links and familiarize yourself with the reference documentation!
71
Basic C++ Syntax Basic Types and Variables
Fundamental Types
All other types are composed of these fundamental types in some way
72
Basic C++ Syntax Basic Types and Variables
Void Type
73
Basic C++ Syntax Basic Types and Variables
Boolean Type
74
Basic C++ Syntax Basic Types and Variables
Signedness modifiers
• signed integers will have signed representation (i.e. they can represent
negative numbers)
• unsigned integers will have unsigned representation (i.e. they can only
represent non-negative numbers)
Size modifiers
• short integers will be optimized for space (at least 16 bits wide)
• long integers will be at least 32 bits wide
• long long integers will be at least 64 bits wide
75
Basic C++ Syntax Basic Types and Variables
By default integers are signed, thus the signed keyword can be omitted
// e and f have the same type
signed int e;
int f;
77
Basic C++ Syntax Basic Types and Variables
#include <cstdint>
78
Basic C++ Syntax Basic Types and Variables
Character Types
Character types represent character codes and (to some extent) integral values
• Identified by C++ keywords signed char and unsigned char
• Minimum width is 8 bit, large enough to represent UTF-8 eight-bit code units
• The C++ type char may either be signed char or unsigned char,
depending on the implementation
• signed char and unsigned char are sometimes used to represent small
integral values
79
Basic C++ Syntax Basic Types and Variables
80
Basic C++ Syntax Basic Types and Variables
81
Basic C++ Syntax Basic Types and Variables
Example
uint16_t i = 257;
uint8_t j = i; // j is 1
if (j) {
/* executed if j is not zero */
}
82
Basic C++ Syntax Basic Types and Variables
83
Basic C++ Syntax Basic Types and Variables
Example
foo.cpp foo.o
int foo(int i) { foo(int):
if ((i + 1) > i) movl $42, %eax
return 42; retq
return 123;
}
84
Basic C++ Syntax Basic Types and Variables
Variables
void foo() {
unsigned i = 0, j;
unsigned meaningOfLife = 42;
}
85
Basic C++ Syntax Basic Types and Variables
Important differences
• Options 1 and 2 simply assign the value of the expression to the variable,
possibly invoking implicit type conversions
• Option 3 results in a compile error if implicit type conversions potentially
result in loss of information
86
Basic C++ Syntax Basic Types and Variables
double a = 3.1415926;
double b(42);
unsigned c = a; // OK: c == 3
unsigned d(b); // OK: d == 42
unsigned e{a}; // ERROR: potential information loss
unsigned f{b}; // ERROR: potential information loss
87
Basic C++ Syntax Basic Types and Variables
Integer Literals
Integer literals represent constant values embedded in the source code
• Decimal: 42
• Octal: 052
• Hexadecimal: 0x2a
• Binary: 0b101010
88
Basic C++ Syntax Basic Types and Variables
Floating-point literals
One of the following suffixes may be appended to a literal to specify its type
• float suffix: 1.0f or 1.0F
• long double suffix: 1.0l or 1.0L
89
Basic C++ Syntax Basic Types and Variables
Character Literals
One of the following prefixes may be prepended to a literal to specify its type
• UTF-8 prefix: u8'a', u8'b'
• UTF-16 prefix: u'a', u'b'
• UTF-32 prefix: U'a', U'b'
90
Basic C++ Syntax Basic Types and Variables
Any type T in C++ (except function and reference types) can be cv-qualified
• const-qualified: const T
• volatile-qualified: volatile T
• cv-qualifiers can appear in any order, before or after the type
Semantics
• const objects cannot be modified
• Any read or write access to a volatile object is treated as a visible side
effect for the purposes of optimization
• volatile should be avoided in most cases (it is likely to be deprecated in
future versions of C++)
• Use atomics instead (more details later)
91
Basic C++ Syntax Basic Types and Variables
int main() {
int a = 1; // will be optimized out
int b = 2; // will be optimized out
volatile int c = 42;
volatile int d = c + b;
}
main:
movl $42, -4(%rsp) # volatile int c = 42
movl -4(%rsp), %eax # volatile int d = c + b;
addl $2, %eax # volatile int d = c + b;
movl %eax, -8(%rsp) # volatile int d = c + b;
movl $0, %eax # implicit return 0;
ret
92
Basic C++ Syntax Expressions
Expression Fundamentals
Fundamental expressions
• Variable names
• Literals
93
Basic C++ Syntax Expressions
Value Categories
Broadly (and inaccurately) there are two value categories: lvalues and rvalues
• lvalues refer to the identity of an object
• rvalues refer to the value of an object
• Modifiable lvalues can appear on the left-hand side of an assignment
• lvalues and rvalues can appear on the right-hand side of an assignment
94
Basic C++ Syntax Expressions
Operator Explanation
+a Unary plus
-a Unary minus
a + b Addition
a - b Subtraction
a * b Multiplication
a / b Division
a % b Modulo
~a Bitwise NOT
a & b Bitwise AND
a | b Bitwise OR
a ^ b Bitwise XOR
a << b Bitwise left shift
a >> b Bitwise right shift
95
Basic C++ Syntax Expressions
Incorrectly using the arithmetic operators can lead to undefined behavior, e.g.
• Signed overflow (see above)
• Division by zero
• Shift by a negative offset
• Shift by an offset larger than the width of the type
96
Basic C++ Syntax Expressions
Operator Explanation
!a Logical NOT
a && b Logical AND (short-circuiting)
a || b Logical OR (short-circuiting)
a == b Equal to
a != b Not equal to
a < b Less than
a > b Greater than
a <= b Less than or equal to
a >= b Greater than or equal to
97
Basic C++ Syntax Expressions
Operator Explanation
a = b Simple assignment
a += b Addition assignment
a -= b Subtraction assignment
a *= b Multiplication assignment
a /= b Division assignment
a %= b Modulo assignment
a &= b Bitwise AND assignment
a |= b Bitwise OR assignment
a ^= b Bitwise XOR assignment
a <<= b Bitwise left shift assignment
a >>= b Bitwise right shift assignment
Notes
• The left-hand side of an assignment operator must be a modifiable lvalue
• For built-in types a OP= b is equivalent to a = a OP b except that a is only
evaluated once
98
Basic C++ Syntax Expressions
unsigned a, b, c;
a = b = c = 42; // a, b, and c have value 42
if (unsigned d = computeValue()) {
// executed if d is not zero
} else {
// executed if d is zero
}
99
Basic C++ Syntax Expressions
Operator Explanation
++a Prefix increment
--a Prefix decrement
a++ Postfix increment
a-- Postfix decrement
100
Basic C++ Syntax Expressions
Operator Explanation
a?b:c Conditional operator
Semantics
• a is evaluated and converted to bool
• If the result was true, b is evaluated
• Otherwise c is evaluated
The type and value category of the resulting expression depend on the operands
101
Basic C++ Syntax Expressions
102
Basic C++ Syntax Expressions
103
Basic C++ Syntax Expressions
104
Basic C++ Syntax Expressions
105
Basic C++ Syntax Expressions
106
Basic C++ Syntax Statements
Simple Statements
int i = 0;
{ // start of block
int i = 0; // declaration statement
} // end of block, i goes out of scope
int i = 1; // declaration statement
107
Basic C++ Syntax Statements
Scope
int a = 21;
int b = 0;
{
int a = 1; // scope of the first a is interrupted
int c = 2;
b = a + c + 39; // a refers to the second a, b == 42
} // scope of the second a and c ends
b = a; // a refers to the first a, b == 21
b += c; // ERROR: c is not in scope
108
Basic C++ Syntax Statements
If Statement (1)
if (init-statement; condition)
then-statement
else
else-statement
Explanation
• If condition evaluates to true after conversion to bool, then-statement is
executed, otherwise else-statement is executed
• Both init-statement and the else branch can be omitted
• If present, init-statement must be an expression or declaration statement
• condition must be an expression statement or a single declaration
• then-statement and else-statement can be arbitrary (compound) statements
109
Basic C++ Syntax Statements
If Statement (2)
The init-statement form is useful for local variables only needed inside the if
Equivalent formulation
{
unsigned value = computeValue();
if (value < 42) {
// do something
} else {
// do something else
}
}
110
Basic C++ Syntax Statements
If Statement (3)
In nested if-statements, the else is associated with the closest if that does not
have an else
// INTENTIONALLY BUGGY!
if (condition0)
if (condition1)
// do something if (condition0 && condition1) == true
else
// do something if condition0 == false
// Working as intended
if (condition0) {
if (condition1)
// do something if (condition0 && condition1) == true
} else {
// do something if condition0 == false
}
111
Basic C++ Syntax Statements
Explanation
• condition may be an expression or single declaration that is convertible to an
enumeration or integral type
• The body of a switch statement may contain an arbitrary number of
case constant: labels and up to one default: label
• The constant values for all case: labels must be unique
• If condition evaluates to a value for which a case: label is present, control is
passed to the labelled statement
• Otherwise, control is passed to the statement labelled with default:
• The break; statement can be used to exit the switch
112
Basic C++ Syntax Statements
Regular example
switch (computeValue()) {
case 21:
// do something if computeValue() was 21
break;
case 42:
// do something if computeValue() was 42
break;
default:
// do something if computeValue() was != 21 and != 42
break;
}
113
Basic C++ Syntax Statements
switch (computeValue()) {
case 21:
case 42:
// do something if computeValue() was 21 or 42
break;
default:
// do something if computeValue() was != 21 and != 42
break;
}
114
Basic C++ Syntax Statements
While Loop
while (condition)
statement
Explanation
• Executes statement repeatedly until the value of condition becomes false.
The test takes place before each iteration.
• condition may be an expression that can be converted to bool or a single
declaration
• statement may be an arbitrary statement
• The break; statement may be used to exit the loop
• The continue; statement may be used to skip the remainder of the body
115
Basic C++ Syntax Statements
Do-While Loop
do
statement
while (condition);
Explanation
• Executes statement repeatedly until the value of condition becomes false.
The test takes place after each iteration.
• condition may be an expression that can be converted to bool or a single
declaration
• statement may be an arbitrary statement
• The break; statement may be used to exit the loop
• The continue; statement may be used to skip the remainder of the body
116
Basic C++ Syntax Statements
unsigned i = 42;
do {
// executed once
} while (i < 42);
117
Basic C++ Syntax Statements
Explanation
• Executes init-statement once, then executes statement and
iteration-expression repeatedly until condition becomes false
• init-statement may either be an expression or declaration
• condition may either be an expression that can be converted to bool or a
single declaration
• iteration-expression may be an arbitrary expression
• All three of the above statements may be omitted
• The break; statement may be used to exit the loop
• The continue; statement may be used to skip the remainder of the body
118
Basic C++ Syntax Statements
119
Basic C++ Syntax Functions
Functions in C++
• Associate a sequence of statements (the function body) with a name
• Functions may have zero or more function parameters
• Functions can be invoked using a function-call expression which initializes the
parameters from the provided arguments
name ( argument-list );
120
Basic C++ Syntax Functions
unsigned meaningOfLife() {
// extremely complex computation
return 42;
}
int main() {
// run the program
}
121
Basic C++ Syntax Functions
122
Basic C++ Syntax Functions
Argument Passing
unsigned square(unsigned v) {
v = v * v;
return v;
}
int main() {
unsigned v = 8;
unsigned w = square(v); // w == 64, v == 8
}
C++ differs from other programming languages (e.g. Java) in this respect
• Parameters can explicitly be passed by reference (more details later)
• Essential to keep argument-passing semantics in mind, especially when
used-defined classes are involved (more details later)
123
Basic C++ Syntax Functions
Default Arguments
A function definition can include default values for some of its parameters
• Indicated by including an initializer for the parameter
• After a parameter with a default value, all subsequent parameters must have
default values as well
• Parameters with default values may be omitted when invoking the function
int main() {
int x = foo(1); // x == 6
int y = foo(1, 1); // y == 5
int z = foo(1, 1, 1); // z == 3
}
124
Basic C++ Syntax Functions
125
Basic C++ Syntax Functions
Valid example
int main() {
foo(1u); // calls foo(unsigned)
foo(1.0f); // calls foo(float)
}
126
Basic C++ Syntax Basic IO
Basic IO (1)
#include <iostream>
// ----------------------------------
int main() {
unsigned i = 42;
std::cout << "The value of i is " << i << std::endl;
}
127
Basic C++ Syntax Basic IO
Basic IO (2)
#include <iostream>
// ----------------------------------
int main() {
std::cout << "Please enter a value: ";
unsigned v;
std::cin >> v;
std::cout << "You entered " << v << std::endl;
}
128