CS1021C Exam Prep
allow the programmer to create an alias for a data type, and use the aliased name instead of the actual type name.
Typedefs
The result of using an uninitialized variable is an example of ___________
Undefined behavior
the result of executing code whose behavior is not well defined by the C++ language
Undefined behavior
integers that can only hold non-negative whole numbers
Unsigned integers
allows you to inspect the value of a variable while the program is executing in debug mode
Watching a variable
a term that refers to characters that are used for formatting purposes, refers primarily to spaces, tabs, and newlines
Whitespace
Create header files that hold constants like this: #ifndef CONSTANTS_H #define CONSTANTS_H // define your own namespace to hold constants namespace constants { constexpr double pi { 3.14159 }; constexpr double avogadro { 6.0221413e23 }; constexpr double my_gravity { 9.2 }; // m/s^2 -- gravity is light on this planet // ... other related constants } #endif Now type X
X
Will this compile? Y/N int count=0; for ( ; count < 10; ) { std::cout << count << ' '; ++count; }
Y
Will this compile? Y/N struct Employee { short id; int age; double wage; };
Y
Will this compile? Y/N struct Rectangle { double length{ 1.0 }; double width{ 1.0 }; };
Y
Will this compile? Y/N void passArray(int prime[5]) { prime[0] = 11; prime[1] = 7; prime[2] = 5; prime[3] = 3; prime[4] = 2; }
Y
Will this error? Y/N int value{ 5 }; const int& ref{ value }; ref = 7;
Y
Will this error? Y/N #include <iostream> #include <iterator> void printSize(int array[]) { std::cout << std::size(array) << '\n'; int main() { int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; std::cout << std::size(array) << '\n'; printSize(array); return 0; }
Y
Will this error? Y/N #include <iostream> int main() { std::cout << "The sum of 3 and 4 is: " << add(3, 4) << '\n'; return 0; } int add(int x, int y) { return x + y; }
Y
Will this error? Y/N class DateClass { int m_month; int m_day; int m_year; }; int main() { DateClass date; date.m_month = 10; // error date.m_day = 14; // error date.m_year = 2020; // error return 0; }
Y
Will this error? Y/N const int value = 5; const int *ptr = &value; " *ptr = 6;
Y
Will this error? Y/N const int y{ 7 }; int &ref2{ y };
Y
Will this error? Y/N double array[5]{ 9, 7, 5, 3, 1 }; int *ptr{ array };
Y
Will this error? Y/N int &ref;
Y
Will this error? Y/N int iValue{ 5 }; double dValue{ 7.0 }; int *iPtr{ &iValue }; double *dPtr{ &dValue }; iPtr = &dValue;
Y
Will this error? Y/N int length{}; std::cin >> length; int array[length];
Y
Will this error? Y/N int temp{ 5 }; const int length{ temp }; int array[length]{};
Y
Will this error? Y/N int value = 5; const int *ptr = &value; *ptr = 6;
Y
Will this error? Y/N int value{ 45 }; int *ptr{ &value }; *ptr = &value;
Y
Will this error? Y/N void foo(const std::string &x) { x = "hello"; }
Y
Will this snippet error? Y/N int getRandomValue(); double getRandomValue();
Y
Will this throw a compiler error? Y/N int width{ 4.5 };
Y
Y/N Is this a valid identifier? IlIKeCaKe
Y
Y/N Is this a valid identifier? _playerOne
Y
Y/N Is this a valid identifier? the_cube_is_cool
Y
are these the same? Y/N (*ptr).age = 5; ptr->age = 5;
Y
find() is a function. Are these expressions equivalent? Y/N find(std::begin(arr), std::end(arr), 20) find(arr, arr + std::size(arr), 20)
Y
will this error? Y/N std::array<int> myArray { 9, 7, 5, 3, 1 };
Y
Will this compile? Y/N int array[3][5]{};
Y (all values set to zero)
Will this function compile? Y/N int getValue(void) int x; std::cin >> x; return x; }
Y (but it is deprecated)
In an array variable declaration, we use __________________ to tell the compiler both that this is an array variable (instead of a normal variable), as well as how many variables to allocate (called the array length).
square brackets ([])
An instruction in a computer program that tells the computer to perform an action
statement
tryAgain: // this is a ______________
statement label
Local variables have ____________________, which means they are in scope from their point of definition to the end of the block they are defined within.
block scope
Variables with _______________ / ___________ can only be accessed within the block in which they are declared (including nested blocks). This includes Local variables, Function parameters, User-defined type definitions (such as enums and classes) declared inside a block
block scope, local scope
What is the default type of the boolean value literals?
bool
What is the one boolean type?
bool
Declare a boolean variable with the name b and the value false
bool b {false};
the two types of labels (switch statements)
case label, default label
What is the default type of char value literals?
char
Create a vector of ints named array with 5 values.
std::vector<int> array(5); (uses direct initialization)
declare a vector with name array2, type int, and values 9,7,5,3,1 (using uniform initialization)
std::vector<int> array2 { 9, 7, 5, 3, 1 };
When used as part of an identifier declaration, the static and extern keywords are called ___________________. In this context, they set the storage duration and linkage of the identifier
storage class specifiers
a collection of sequential characters
string
a collection of sequential characters, not a fundamental data type, uses double quotes
string
what library has the getline() function?
string
When we are done with a dynamically allocated variable, we need to explicitly tell C++ to free the memory for reuse. For single variables, this is done via the scalar (non-array) form of the __________ operator:
delete
What is the default type of floating point value literals?
double
Zero-Initialize a double with identifier dPtr
double *dPtr{};
To make a global variable external (and thus accessible by other files), we can use the ___________ keyword
extern
Write a forward declaration for this variable: int g_x{2};
extern int g_x;
An identifier ___________ with linkage can be accessed anywhere within the file it is declared, or other files (via a forward declaration). This includes: Functions, Non-const global variables (initialized or uninitialized), Extern const global variables, Inline const global variables, User-defined type definitions (such as enums and classes) declared inside a namespace or in the global scope
external
Global variables with external linkage are sometimes called ______________
external variables
non-constant global identifiers have _____________ linkage by default, but can be given ______________ linkage via the _______________ keyword
external, internal, static
When used with cin, >> is called the ____________
extraction operator
A ____ suffix is used to denote a literal of type float
f
What suffixes can you add to an floating point value literal to make it float?
f, F
One of the most common use cases for blocks is in conjunction with ______________
if statements
your class has no constructors, C++ will automatically generate a public default constructor for you. This is sometimes called an ________________________
implicit constructor
When an identifier can be accessed
in scope
If you wanted to access cout without using an explicit namespace qualifier what line would you have to put in your code?
using namespace std;
std::vector comes from what header?
vector
To tell the compiler that a function does not return a value, a return type of __________ is used
void
What is the one Void type?
void
Write a function (on one line) named change that sets the passed in int to 5. It should gave a void return type and the parameter should be named test.
void change(int &test) { test = 5; }
Write the forward declaration for a function with void return type and the name foo. It should take a reference to an int with the identifier num
void foo(int &num);
Write the forward declaration for a function with void return type and the name foo. It should take a reference to an array of ints of length 5 with name array
void foo(int (&array)[5]);
Write the forward declaration for a function with void return type and the name foo. It should have one parameter: a reference to a pointer to an int with the identifier ptr
void foo(int *&ptr);
allows us to explicitly pick which namespace we want to look in
scope resolution operator
define a signed short with the identifier s;
short s;
What are the four integer types?
short, int, long, long long
A function or expression is said to have a ____________ if it does anything that persists beyond the life of the function or expression itself.
side effect
By default, integers are (Signed/unsigned)
signed
Character literals are always placed between _________________
single quotes
a unary operator that takes either a type or a variable, and returns its size in bytes
sizeof operator
Without using std::size write an expression to get the length of an a array (with at least on value), the array's identifier is array
sizeof(array)/sizeof(array[0])
operators that act on two operands
Binary operators
What is the ^ operator?
Bitwise XOR
an array of characters that uses a null terminator.
C-style string
float f { float(i1) / i2 }; What type of cast is this? Is it recommended?
C-style, no
If -1 was entered into a 8-bit unsigned int what value would be stored
255
class Foo { private: public: Foo() { // code to do A } Foo(int value) //What should this line be to call the first constructor? { // code to do B } };
Foo(int value): Foo{}
Will this error? If not, what prints? switch (2) { case 1: std::cout << 1 << ','; case 2: // Match! std::cout << 2 << '\,'; case 3: std::cout << 3 << ','; case 4: std::cout << 4 << ','; default: std::cout << 5 << ','; }
N, 2,3,4,5
Will this error? Y/N If not, what does it print? int array []{ 9, 7, 5, 3, 1 }; std::cout << array[1] << ','; std::cout << *(array+1);
N, 7,7
Will this error? Y/N If not, is iPtr7 a pointer? Y/N int* iPtr6, iPtr7;
N, N
Will this error? Y/N If not, will it work as intended? Y/N #include <iostream> void printSize(int array[]) { std::cout << sizeof(array) / sizeof(array[0]); } int main() { int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; std::cout << sizeof(array) / sizeof(array[0]) << ','; printSize(array); return 0; }
N, N
Will this error? If not, what will it print? (A ________) int array[5]{ 9, 7, 5, 3, 1 }; std::cout << array;
N, pointer
Will this compile? #include <iostream> int main() { int x = 5; std::cout << (x != 5 ? x : "x is 5"); return 0; }
No (The type of the expressions must match or be convertible)
executes the next statement in the normal execution path of the program, and then pauses execution. If the statement contains a function call, this executes the function and returns control to you after the function has been executed.
Step over
the name for a set of related debugging features that allow you to step through our code statement by statement
Stepping
T/F enums are ended with semicolons.
T
T/F? A name declared in a namespace won't be mistaken for an identical name declared in another scope.
T
T/F? All definitions also serve as declarations
T
T/F? Although constexpr variables can be given external linkage via the extern keyword, they can not be forward declared, so there is no value in giving them external linkage.
T
T/F? Angled brackets are used to tell the preprocessor that we are including a header file that was included with the compiler
T
T/F? Breaking "int x{ 2 + 3 };" into its syntax is "type identifier { expression };"
T
T/F? For a while loop, if the loop condition is initially false, the while loop will not execute at all
T
T/F? Header files allow us to put declarations in one location and then import them wherever we need them
T
T/F? Local variables are destroyed in the opposite order of creation at the end of the set of curly braces in which it is defined (or for a function parameter, at the end of the function).
T
T/F? Nested functions are illegal in C++.
T
T/F? Order of operation execution follows PEMDAS.
T
T/F? Prefer '\n' over std::endl when outputting text to the console.
T
T/F? Quoted text separated by nothing but whitespace (spaces, tabs, or newlines) will be concatenated
T
T/F? References must be initialized when created:
T
T/F? Signed integer overflow will result in undefined behavior.
T
T/F? Static members are not associated with class objects
T
T/F? The #define directive only affects from where it is defined to the bottom of the file
T
T/F? The C++ language allows you to perform integer addition or subtraction operations on pointers
T
T/F? The arrow operator does the same as an indirection followed by the . member selection operator
T
T/F? The double-quotes tell the preprocessor that this is a user-defined header file we are supplying.
T
T/F? Trying to divide by 0 (or 0.0) will generally cause your program to crash
T
T/F? Using the address-of operator on a reference returns the address of the value being referenced:
T
T/F? We can use brace or direct initialization for class constructors with parameters
T
T/F? references can be constant
T
3 logical operators (symbols)
!, &&, ||
!(x || y) is equivalent to ___________
!x && !y
!(x && y) is equivalent to __________
!x || !y
A preprocessor directive that will replace all occurrences of Joe with Bob
#define Joe Bob
the directive that can be used to create a macro
#define directive
A preprocessor directive that will replace all occurrences of the word spot with nothing
#define spot
Ends the #ifdef and # ifndef directives
#endif
What preprocessor directive would you include to be able to use strings?
#include <string>
the directive where the preprocessor replaces the directive with the contents of the included file
#include directive
Will this compile? If so, what's the output? if not, type N. #include <iostream> int initx(); // forward declaration int inity(); // forward declaration int g_x{ initx() }; int g_y{ inity() }; int initx() { return g_y; } int inity() { return 5; } int main() { std::cout << g_x << ' ' << g_y << '\n'; }
0 5
Put ____ before a number to make it binary
0b
Put ____ before a number to make it hexadecimal
0x
What is the output when you input 3.9 into this program? If there is an error, write E; if not, write the output. #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; }
3
If 260 was entered into a 8-bit unsigned int what value would be stored
4
Will this error? Y/N const int& ref3{ 6 };
N
What does cin stand for?
character input
Each of the variables in an array
element
Write the function that makes this work #include <array> #include <iostream> int main() { std::array<int, 25> array; // Set the element of array with index 10 to the value 5 getElement(array, 10) = 5; std::cout << array[10] << '\n'; return 0; }
int& getElement(std::array<int, 25> &array, int index) { return array[index]; }
Forward declare a function with no parameters, the identifier doSomething, and a return type of an int pointer
int* doSomething();
a number that can be written without a fractional component
integer
a debugger that integrates into the code editor
integrated debugger
Const and constexpr global variables have __________ linkage by default
internal
What library contains cout, cin, and endl?
iostream (input/output library)
What suffixes can you add to an floating point value literal to make it long double?
l, L
happen when your program loses the address of some bit of dynamically allocated memory before giving it back to the operating system. When this happens, your program can't delete the dynamically allocated memory, because it no longer knows where it is. The operating system also can't use this memory, because that memory is considered to be still in use by your program.
memory leak
an operator that returns the remainder after doing an integer division
modulus (%)
An array of arrays is called a __________________________________.
multidimensional array
Write an expression statement for the length of this array std::array<int> myArray { 9, 7, 5, 3, 1 };
myArray.size();
write an expression that gets the length of a string variable named myName
myName.length()
At each number say if the line is okay/illegal switch (1) { int a; // 1 int b{ 5 }; // 2 case 1: int y; // 3 y = 4; // 4 break; case 2: y = 5; // 5 break; case 3: int z{ 4 }; // 6 break; default: std::cout << "default case\n"; break; }
okay, illegal, okay, okay, okay, illegal
the input values in an operation
operands
a mathematical calculation involving zero or more input values
operation
The specific operation to be performed is denoted by a construct called ___________
operator
When an identifier can not be accessed
out of scope
Parameters that are only used for returning values back to the caller are called _________
out parameters
The two special identifiers
override, final
When a function is called, all of the parameters of the function are created as variables, and the value of each of the arguments is copied into the matching parameter. This process is called _____________
pass by value
When an argument is ____________, the argument's value is copied into the value of the corresponding function parameter.
passed by value
a variable that holds a memory address as its value.
pointer
the hidden this keyword thing is a ____________
pointer
A ________________ is a (non-const) pointer that points to a constant value.
pointer to a const value
What functions sorts an array in ascending order? What header is it in?
std::sort(), algorithm
address-of operator (&) is (unary/binary)
unary
a special type of pointer that can be pointed at objects of any data type
void pointer
allows you to examine the value of variables or expressions.
watch window
A ______a_________ is declared using the _____b______ keyword. When a _______a___________ is executed, the expression is evaluated. If the expression evaluates to true (non-zero), the statement executes.
while statement, while
Passing an array to a function and changing a value (will/won't) edit the original array
will
The modulus operator can also work with negative operands. x % y always returns results with the sign of _____ (C++11)
x
int x{ 5 }; int &y{ x }; int &z{ y }; z is a reference to (x/y)
x
add parentheses to each expression to make it clear how the compiler will evaluate the expression x = 3 + 4 + 5;
x = ((3 + 4) + 5);
add parentheses to each expression to make it clear how the compiler will evaluate the expression x = y = z;
x = (y = z);
type xyz Prefer pass by reference to pass by address whenever applicable.
xyz
add parentheses to each expression to make it clear how the compiler will evaluate the expression z *= ++y + 5;
z *= ((++y) + 5);
The preprocessor directive that allows the preprocessor to check whether an identifier has been previously #defined. If so, the code between this directive and matching #endif is compiled. If not, the code is ignored.
#ifdef
The preprocessor directive that allows the preprocessor to check whether an identifier has not been previously #defined. If so, the code between this directive and matching #endif is compiled. If not, the code is ignored.
#ifndef
Rewrite .cpp file so that it is a header file that stores the value for each constant. (not inline though) #include "constants.h" namespace constants { extern const double pi { 3.14159 }; extern const double avogadro { 6.0221413e23 }; extern const double my_gravity { 9.2 }; }
#ifndef CONSTANTS_H #define CONSTANTS_H namespace constants { constexpr double pi { 3.14159 }; constexpr double avogadro { 6.0221413e23 }; constexpr double my_gravity { 9.2 }; } #endif
Write the header file that would go with this code. (Note: this generally isn't the preferred way of storing constants) #include "constants.h" namespace constants { // actual global variables extern const double pi { 3.14159 }; extern const double avogadro { 6.0221413e23 }; extern const double my_gravity { 9.2 }; // m/s^2 -- gravity is light on this planet }
#ifndef CONSTANTS_H #define CONSTANTS_H namespace constants { extern const double pi; extern const double avogadro; extern const double my_gravity; } #endif
What would you type to use a header file name add.h?
#include "add.h"
What is the header for most math operations (write as preprocessor directive)
#include <cmath>
What line do you have to include in your program to use fixed-width integers
#include <cstdint>
To use std::setprecision() what line of code must be included in your file?
#include <iomanip>
add parentheses to each expression to make it clear how the compiler will evaluate the expression a || b && c || d;
(a || (b && c)) || d;
You can use operator ____ to concatenate two strings together (symbol)
+
What are the binary arithmetic operators (just symbols)?
+, -, *, /, %
You can use operator ____ to append a string to the end of an existing string (symbol)
+=
What are the arithmetic assignment operators?
+=, -=, *=, /=, %=
What is the output when you input -3 into this program? If there is an error, write E; if not, write the output. #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; }
-3
What function can be used with std::array and std::vector that is similar to operator[], but does bounds checking
.at()
What function can be used with std::array and std::vector to get their size
.size()
Each enumerator is automatically assigned an integer value based on its position in the enumeration list. By default, the first enumerator is assigned the integer value ______, and each subsequent enumerator has a value one greater than the previous enumerator.
0
If 256 was entered into a 8-bit unsigned int what value would be stored
0
If you enter "true" for the cin, what printed after "You entered: "? #include <iostream> int main() { bool b{}; // default initialize to false std::cout << "Enter a boolean value: "; std::cin >> b; std::cout << "You entered: " << b << '\n'; return 0; }
0
Put ____ before a number to make it octal
0
What is the 4th value of this array? int array[5]{ 7, 4, 5 };
0
What is the output when you input hello into this program? If there is an error, write E; if not, write the output. #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; }
0
What is the output when you input the character "h" into this program? If there is an error, write E; if not, write the output. #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; }
0
When cin gets a failed input the variable will be set to ___________
0
When implicit conversion is allowed (such as in copy initialization), what integers will result in a boolean being false?
0
For each of the following programs, state whether they (1) fail to compile, (2) fail to link, fail both, or (3) compile and link successfully. #include <iostream> int add(int x, int y); int main() { std::cout << "3 + 4 + 5 = " << add(3, 4, 5) << '\n'; return 0; } int add(int x, int y) { return x + y; }
1
For each of the following programs, state whether they (1) fail to compile, (2) fail to link, fail both, or (3) compile and link successfully. #include <iostream> int add(int x, int y); int main() { std::cout << "3 + 4 + 5 = " << add(3, 4, 5) << '\n'; return 0; } int add(int x, int y, int z) { return x + y + z; }
1
int n{7}; int d{4}; std::cout << n / d; What will this snippet print?
1
What is the value of width for r? struct Rectangle { double length{ 1.0 }; double width{ 1.0 }; }; int main() { Rectangle r; }
1.0
int n{7}; double d{4}; std::cout << n / d; What will this snippet print?
1.75
one definition rule
1.Within a given file, a function, object, type, or template can only have one definition. 2.Within a given program, an object or normal function can only have one definition. This distinction is made because programs can have more than one file (we'll cover this in the next lesson). 3.Types, templates, inline functions, and variables are allowed to have identical definitions in different files. We haven't covered what most of these things are yet, so don't worry about this for now -- we'll bring it back up when it's relevant.
What does this log? #include <iostream> int main() { std::cout << true; std::cout << !true; return 0; }
10
What is age set to? Employee struct { short id; int age; int wage; }; Employee joe{ 10, 11, 12};
11
What is the output? std::cout << 2 + 3 * 4;
14
For each of the following programs, state whether they (1) fail to compile, (2) fail to link, fail both, or (3) compile and link successfully. #include <iostream> int add(int x, int y); int main() { std::cout << "3 + 4 + 5 = " << add(3, 4) << '\n'; return 0; } int add(int x, int y, int z) { return x + y + z; }
2
Is 1, 2, both or neither correct? (these are forward declarations) enum Color; // 1 enum Color : int; // 2
2
Local variables inside the function body should be (1) defined at the beginning of the function or (2) defined as close to their first use as reasonable
2
What will this print? #include <iostream> void incrementAndPrint() { int value{ 1 }; ++value; std::cout << value << ','; } int main() { incrementAndPrint(); incrementAndPrint(); incrementAndPrint(); return 0; }
2,2,2
What will this print? #include <iostream> void incrementAndPrint() { static int s_value{ 1 }; ++s_value; std::cout << s_value << ','; } int main() { incrementAndPrint(); incrementAndPrint(); incrementAndPrint(); return 0; }
2,3,4
What is the output when you input 3000000000000 into this program? If there is an error, write E; if not, write the output. #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; }
2147483647 (max int)
For each of the following programs, state whether they (1) fail to compile, (2) fail to link, fail both, or (3) compile and link successfully. #include <iostream> int add(int x, int y, int z); int main() { std::cout << "3 + 4 + 5 = " << add(3, 4, 5) << '\n'; return 0; } int add(int x, int y, int z) { return x + y + z; }
3
What does this output? #include <iostream> int main() { int x{ 1 }; int y{ 2 }; std::cout << (++x, ++y); return 0; }
3
What is the nesting level of main() int main() { std::cout << "Enter an integer: "; int value {}; std::cin >> value; if (value > 0) { if ((value % 2) == 0) { std::cout << value << " is positive and even\n"; } else { std::cout << value << " is positive and odd\n"; } } return 0; }
3
What is the output when you input 3.2 into this program? If there is an error, write E; if not, write the output. #include <iostream> // for std::cout and std::cin int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; }
3
Which of these is false 1) The destructor must have the same name as the class, preceded by a tilde (~) 2) The destructor can not take arguments 3) The destructor may not call other functions 4) The destructor has no return type.
3
What does this print? enum Color { color_black, color_red, color_blue, color_green, color_white, color_cyan, color_yellow, color_magenta }; Color paint(color_white); std::cout << paint;
4
void printSize(int array[]) { std::cout << sizeof(array) << '\n'; // What will this print? } int main() { int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; std::cout << sizeof(array) << '\n'; // will print 32 printSize(array);return 0; }
4
What does this output? #include <iostream> int main() { int x { 5 }; int y = --x; std::cout << x << ' ' << y; return 0; }
4 4
What does this output? #include <iostream> int main() { int x { 5 }; int y = x--; std::cout << x << ' ' << y; return 0; }
4 5
What does this print? #include <iostream> class A { public: A(int x) { std::cout << x;} }; class B { private: A m_a; public: B(int y) : m_a{ y-1 } { std::cout << 'y'; } }; int main() { B b{ 5 }; return 0; }
45
What will this print? Y/N #include <iostream> void changeArray(int *ptr) { *ptr = 5; } int main() { int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; changeArray(array); std::cout << array[0]; return 0; }
5
What does this output? #include <iostream> int main() { int x{ 5 }; int y{ 5 }; std::cout << x++ << ' ' << y-- << ' '; std::cout << x << ' ' << y << ' '; return 0; }
5 5 6 4
#include <iostream> void foo(int *ptr) { *ptr = 6; } int main() { int value{ 5 }; std::cout << "value = " << value << '\n'; foo(&value); std::cout << "value = " << value << '\n'; return 0; } The above snippet prints: value = ___a___ value = ___b___
5, 6
Will this compile? If so, What will this print? If not., type N. #include <iostream> int main() { int apples { 5 }; { std::cout << apples << ','; int apples{ 0 }; apples = 10; std::cout << apples << '\n'; } std::cout << apples << '\n'; return 0; } // outer block apples destroyed
5,10,5
What integer value is assigned to color_yellow? enum Color { color_black, color_red, color_blue, color_green, color_white, color_cyan, color_yellow, color_magenta, };
6
What will print? int value1{ 5 }; int value2{ 6 }; int &ref{ value1 }; ref = value2; value2++; cout << ref;
6 (ref still references value1)
What does this output? #include <iostream> int main() { int x{ 5 }; int y{ 5 }; std::cout << ++x << ' ' << --y << ' '; std::cout << x << ' ' << y << ' '; return 0; }
6 4 6 4
What does this output? #include <iostream> int main() { int x { 5 }; int y = x++; std::cout << x << ' ' << y; return 0; }
6 5
What does this output? #include <iostream> int main() { int x { 5 }; int y = ++x; std::cout << x << ' ' << y; return 0; }
6 6
int main() { int value{ 5 }; int &ref{ value }; value = 6; ref = 7; std::cout << value; // prints 7 ++ref; std::cout << value; // prints 8 return 0; } What does this print?
78
Write an expression that accesses the global variable "value", given that the variable is being shadowed.
::value
the assignment operator
=
the equality operator
==
The 6 relational operators (symbols)
>, <, >=, <=, ==, !=
defines a particular way to represent English characters (plus a few other symbols) as numbers between 0 and 127
ASCII
the number given to an ASCII character
ASCII code
type AVOID GLOBAL VARIABLES
AVOID GLOBAL VARIABLES
determine who has access to the members that follow the specifier
Access specifiers (like private and public)
happens for function parameters and local variables. Memory for these types of variables is allocated when the relevant block is entered, and freed when the block is exited, as many times as necessary
Automatic memory allocation
float f { (float)i1 / i2 }; What type of cast is this? Is it recommended?
C-style, no
enum Color { color_black, color_red, color_blue, color_green, color_white, color_cyan, color_yellow, color_magenta, }; Based on this enum use copy initialization, direct initialization, and direct brace initialization to define a variable of this type, the name paint, and the value of white.
Color paint = color_white; Color paint(color_white); Color paint{color_white};
constants whose initialization values can be resolved at compile-time
Compile-time constants
What type of initialization is this? int height = { 6 };
Copy brace initialization
What type of initialization is this? int width = 5;
Copy initialization
Write a statement that forces the compiler to create a default constructor The class type is Date.
Date() = default;
a technique whereby the programmer tries to anticipate all of the ways the software could be misused. These misuses can often be detected and mitigated.
Defensive programming
What form of initialization should you be using (assume your compiler is C++11 compliant)?
Direct brace initialization
What type of initialization is this? int width{ 5 };
Direct brace initialization
What type of initialization is has better performance? Copy initialization or Direct initialization
Direct initialization
What type of initialization is this? int width( 5 );
Direct initialization
the std::pow() function takes in and returns what data type?
Double
determines where a variable is created and destroyed
Duration
a way for running programs to request memory from the operating system when needed. This memory does not come from the program's limited stack memory -- instead, it is allocated from a much larger pool of memory managed by the operating system called the heap.
Dynamic memory allocation
Declare a variable of type employee and with the identifier e1. Make the name Alex, id 1, and wage 25.00 class Employee { public: std::string m_name{}; int m_id{}; double m_wage{}; // Print employee information to the screen void print() { std::cout << "Name: " << m_name << " Id: " << m_id << " Wage: $" << m_wage << '\n'; } };
Employee e1 { "Alex", 1, 25.00 };
the process of keeping the details about how an object is implemented hidden away from users of the object. Instead, users of the object access the object through a public interface. In this way, users are able to use the object without having to understand how it is implemented.
Encapsulation (also called information hiding)
When a program is run, where does execution start?
Execution starts with the first statement inside the main function
happens when the user uses a type cast to explicitly convert a value from one type to another type
Explicit type conversion
T/F comparison operators have higher precedence than non-assignment arithmetic operators
F
T/F? Deleting a null pointer will cause an error
F
T/F? Double Quotes are used to tell the preprocessor that we are including a header file that was included with the compiler
F
T/F? Expressions end in a semicolon
F
T/F? In C++, direct memory access is allowed
F
T/F? Special identifiers are reserved.
F
T/F? Using directives are preprocessor directives.
F
T/F? When using integer division it will round the result if it is fractional
F
T/F? class declarations do not require a semicolon
F
T/F? const variables cannot be initialized from other variables
F
T/F? static casting does range checking
F
T/F? structs cannot contain structs
F
T/F? the default label is required
F
T/F? the size of the integer variables are fixed
F
T/F? using declaration and using directive do not follow normal block scoping rules
F
T/F? you can resize a dynamically allocated array
F
T/F? In this function call, someFunction(a(), b()); a() will be called then b() will be called
F (Depends on the architecture)
T/F? If the initializer list is omitted, all of the elements of an array will always be uninitialized,
F (If the initializer list is omitted, the elements are uninitialized, unless they are a class-type like std::string)
T/F? If you forward declare a function it will error when being compiled.
F (compiles ok, fails when linking)
T/F? std::cin only accepts two inputs for Boolean variables: true or false
F (only 0 or 1)
T/F? % has a higher precedence than *
F (same)
T/F? For references of structs, you need to use the arrow operator to access embers
F (that is for pointer, use the member selection operator, .)
T/F? when using cin, only the first input character is extracted into variable if multiple are entered. The other characters are just ignored.
F (the first sentence is true, but the second is not. The subsequent characters are left in the input buffer so if you call cin again it will use the next typed character)
five step process to approach debugging
Find the root cause Understand the problem Determine a fix Repair the issue Retest
enum class Fruit { banana, apple }; Fruit banana{ /*what goes here?*/ };
Fruit::banana
a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters.
Function overloading
functions that return the value of a private member variable
Getters (also sometimes called accessors)
What does this print? #include <iostream> // for std::cout int main() { std::cout << "Hi!"; std::cout << "My name is Alex."; return 0; }
Hi!My Name is Alex.
if (condition) true_statement; else false_statement; This is a form of a ________________
If-else
performed whenever one data type is expected, but a different data type is supplied
Implicit type conversion
___________________ is performed whenever one data type is expected, but a different data type is supplied. If the compiler can figure out how to do the conversion between the two types, it will. If it doesn't know how, then it will fail with a compile error.
Implicit type conversion (also called automatic type conversion or coercion)
What is the difference between initialization and assignment?
Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.
the process of an object being created and assigned a memory address
Instantiation
char name[]{ "Jason" }; // C-style string (also an array) std::cout << *name << '\n'; // will print __________
J
What will the output of this code be if compiled and ran? #include <iostream> #define PRINT_JOE int main() { #ifdef PRINT_JOE std::cout << "Joe\n"; #endif #ifdef PRINT_BOB std::cout << "Bob\n"; #endif return 0; }
Joe
What will the output of this code be if compiled and ran? #include <iostream> int main() { std::cout << "Joe"; #if 0 std::cout << "Bob"; std::cout << "Steve"; #endif return 0; }
Joe
What will the output of this code be if compiled and ran? #include <iostream> #define PRINT_JOE int main() { #ifdef PRINT_JOE std::cout << "Joe"; #endif #ifndef PRINT_BOB std::cout << "Bob"; #endif return 0; }
JoeBob
values inserted directly into the code, their values can not be changed dynamically
Literal constants (literals)
provide us with the capability to test multiple conditions
Logical operators
#include <iostream> void changeN(int &ref) { ref = 6; } int main() { int n{ 5 }; std::cout << n << '\n'; changeN(n); // Will this error here? Y/N std::cout << n << '\n'; return 0; }
N
Can you assign enumerators from one type to another type? Y/N
N
Does C++ automatically initialize variables? Y/N
N
Does brace initialization allow for conversions where data would be lost? Y/N
N
Is there a direct or brace assignment? Y/N
N
Is this correct? Y/N std::cout << "x is equal to: " << x << "\n";
N
Is this correct? Y/N std::cout << "x is equal to: " << x << '/n';
N
Is this legal? Y/N double *dPtr{ 0x0012FF7C };
N
Is this legal? Y/N int *ptr{ 5 };
N
Once initialized, can a reference be changed to reference another variable? Y/N
N
Will this compile? Y/N #include <iostream> int main() { do { int selection; std::cout << "Please make a selection: \n"; std::cout << "1) Addition\n"; std::cout << "2) Subtraction\n"; std::cout << "3) Multiplication\n"; std::cout << "4) Division\n"; std::cin >> selection; } while (selection != 1 && selection != 2 && selection != 3 && selection != 4); std::cout << "You selected option #" << selection << "\n"; return 0; }
N
Will this compile? Y/N #include <iostream> int main() { int selection; do { std::cout << "Please make a selection: \n"; std::cout << "1) Addition\n"; std::cout << "2) Subtraction\n"; std::cout << "3) Multiplication\n"; std::cout << "4) Division\n"; std::cin >> selection; } while (selection != 1 && selection != 2 && selection != 3 && selection != 4) std::cout << "You selected option #" << selection << "\n"; return 0; }
N
Will this compile? Y/N #include <iostream> void returnNothing() { std::cout << "Hi" << '\n'; } int main() { returnNothing(); std::cout << returnNothing(); return 0; }
N
Will this compile? Y/N enum Color { red, blue, green }; enum Feeling { happy, tired, blue };
N
Will this compile? Y/N int array[2][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
N
Will this compile? Y/N struct Employee { short id; int age; double wage; }
N
Will this compile? Y/N void passArray(int prime[]) { prime[0] = 11; prime[1] = 7; prime[2] = 5; prime[3] = 3; prime[4] = 2; }
N
Will this compile? Y/N If so, what does it output? #include <iostream> int main() { enum class Color{ red, blue }; enum class Fruit { banana, apple }; Color color{ Color::red }; Fruit fruit{ Fruit::banana }; if (color == fruit) std::cout << "color and fruit are equal\n"; else std::cout << "color and fruit are not equal\n"; return 0; }
N
Will this error? Y/N #include <iostream> int main() { char ch{97}; int i(ch); std::cout << i; return 0; }
N
Will this error? Y/N #include <iostream> void changeArray(int *ptr) { *ptr = 5; } int main() { int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; std::cout << "Element 0 has value: " << array[0] << '\n'; changeArray(array); std::cout << "Element 0 has value: " << array[0] << '\n'; return 0; }
N
Will this error? Y/N #include <iostream> void changeArray(int *ptr) { ptr[1] = 5; } int main() { int array[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; std::cout << "Element 0 has value: " << array[0] << '\n'; changeArray(array); std::cout << "Element 0 has value: " << array[0] << '\n'; return 0; }
N
Will this error? Y/N #include <iostream> class Something { private: int m_value1; double m_value2; char m_value3; public: Something(int value1, double value2, char value3='c') : m_value1{ value1 }, m_value2{ value2 }, m_value3{ value3 } // directly initialize our member variables { } void print() { std::cout << "Something(" << m_value1 << ", " << m_value2 << ", " << m_value3 << ")\n"; } }; int main() { Something something{ 1, 2.2 }; something.print(); return 0; }
N
Will this error? Y/N class Something { private: const int m_value; public: Something(): m_value{ 5 } { } };
N
Will this error? Y/N class Something { private: int data; public: Something(int data) { this->data = data; } };
N
Will this error? Y/N const int value{ 5 }; const int &ref{ value }
N
Will this error? Y/N constexpr int arrayLength{ 5 }; int array[arrayLength]{};
N
Will this error? Y/N enum ArrayElements { max_array_length = 5 }; int array[max_array_length];
N
Will this error? Y/N int * iPtr2{};
N
Will this error? Y/N int array[5]{ 9, 7, 5, 3, 1 }; int *ptr{ array };
N
Will this error? Y/N int value = 5; // value is not constant const int *ptr = &value;
N
Will this error? Y/N int value1 = 5; const int *ptr = &value1; int value2 = 6; ptr = &value2;
N
Will this error? Y/N int value{ 5 }; const int& ref{ value }; value = 6;
N
Will this error? Y/N int value{ 5 }; int &ref{ value };
N
Will this error? Y/N int* iPtr2{};
N
Will this error? Y/N std::cout << "Enter a positive integer: "; std::size_t length{}; std::cin >> length; int *array{ new int[length]{} };
N
Will this throw a compiler error? Y/N int width( 4.5 );
N
Will this work as intended? Y/N class Foo { public: Foo() { //SOMETHING } Foo(int value) { Foo(); } };
N
Will this work as intended? Y/N include <iostream> #include <string> int main() { std::cout << "Enter your full name: "; std::string name{}; std::cin >> name; std::cout << "Enter your age: "; std::string age{}; std::cin >> age; std::cout << "Your name is " << name << " and your age is " << age << '\n'; return 0; }
N
Would it be possible to supply a value for z, without supplying a value for x or y? Y/N void printValues(int x=10, int y=20, int z=30) { //Stuff }
N
Y/N Is this a valid identifier? 1player
N
Y/N Is this a valid identifier? do
N
Y/N Is this a valid identifier? eats pie
N
Y/N Is this a valid identifier? likesCake!
N
class foo { public: void x() { y(); } void y() { }; }; Will this error? Y/N
N
Will this error? Y/N const int length{ temp }; int array[length]{};
N (I think)
Will this error? Y/N #include <iostream> int main() { int arr[]{ 1, 2, 3 }; std::cout << 2[arr] << '\n'; return 0; }
N (The subscript operator [] is identical to an addition and an indirection, the operands can be swapped.)
Will this error? Y/N auto *array{ new int[5]{ 9, 7, 5, 3, 1 } };
N (after C++11 at least, when declaring a dynamic array using an initializer list was allowed)
Will this compile Y/N #include <iostream> // imports the declaration of std::cout int cout() // declares our own "cout" function { return 5; } int main() { using namespace std; // makes std::cout accessible as "cout" cout << "Hello, world!"; // uh oh! Which cout do we want here? The one in the std namespace or the one we defined above? return 0; }
N (ambiguous)
Will this error? Y/N int length{}; std::cin >> length; int* array{ new int[length]{} };
N (but you should static_cast length to std::size_t)
Does this compile? Y/N #include <iostream> using namespace std; int cout() { return 5; } int main() { cout << "Hello, world!"; }
N (compiler can't tell which cout to use)
Will this compile? void someFunction(int x) { int x{}; } int main() { return 0; }
N (name collision)
Will this compile? int main() { int x { 5 }; { int y { 7 }; } ++y; return 0; }
N (out of scope)
Is the array dereferenced? Y/N int array[5]{ 9, 7, 5, 3, 1 }; std::cout << *array;
N (the array is implicitly converted to a pointer, which is dereferenced)
Will this error? Y/N If not, what does y's m_length have the value of. #include <iostream> class Rectangle { private: double m_length{ 1.0 }; double m_width{ 1.0 }; public: Rectangle(double length, double width) : m_length{ length }, m_width{ width } { } Rectangle(double length) : m_length{ length } { } void print() { std::cout << "length: " << m_length << ", width: " << m_width << '\n'; } }; int main() { Rectangle x{ 2.0, 3.0 }; x.print(); Rectangle y{ 4.0 }; y.print(); return 0; }
N, 1.0
Will this error? Y/N If not, what will it print? void printValues(int x, int y=10) { std::cout << x; std::cout << y; } int main() { printValues(1); }
N, 110
Will this compile? Y/N If not, where does it fail (a number)? const int value = 5; //1 int *ptr = &value; // 2 *ptr = 6;//3
N, 2
Will this error? If not, will it work as intended? int& doubleValue(int x) { int value{ x * 2 }; return value; }
N, N (the variable that the returned reference references goes out of scope and is destroyed)
Will this compile? If not, what should the last two lines be replaced with? enum Color { color_black, // assigned 0 color_red, // assigned 1 color_blue, // assigned 2 color_green, // assigned 3 color_white, // assigned 4 color_cyan, // assigned 5 color_yellow, // assigned 6 color_magenta // assigned 7 }; Color color; std::cin >> color;
N, int inputColor; std::cin >> inputColor; Color color{ static_cast<Color>(inputColor) };
Type ONLY DECLARATIONS IN HEADER FILES Header files should generally not contain function and variable definitions, so as not to violate the one definition rule. An exception is made for symbolic constants.
ONLY DECLARATIONS IN HEADER FILES
occur when the loop iterates one too many or one too few times
Off-by-one errors
Why use functions?
Organization -- As programs grow in complexity, having all the code live inside the main() function becomes increasingly complicated. A function is almost like a mini-program that we can write separately from the main program, without having to think about the rest of the program while we write it. This allows us to reduce a complicated program into smaller, more manageable chunks, which reduces the overall complexity of our program. Reusability -- Once a function is written, it can be called multiple times from within the program. This avoids duplicated code ("Don't Repeat Yourself") and minimizes the probability of copy/paste errors. Functions can also be shared with other programs, reducing the amount of code that has to be written from scratch (and retested) each time. Testing -- Because functions reduce code redundancy, there's less code to test in the first place. Also because functions are self-contained, once we've tested a function to ensure it works, we don't need to test it again unless we change it. This reduces the amount of code we have to test at one time, making it much easier to find bugs (or avoid them in the first place). Extensibility -- When we need to extend our program to handle a case it didn't handle before, functions allow us to make the change in one place and have that change take effect every time the function is called. Abstraction -- In order to use a function, you only need to know its name, inputs, outputs, and where it lives. You don't need to know how it works, or what other code it's dependent upon to use it. This lowers the amount of knowledge required to use other people's code (including everything in the standard library).
involves passing the address of the argument variable rather than the argument variable itself
Passing an argument by address
instructions that start with a # symbol and end with a newline (NOT a semicolon), tell the preprocessor to perform specific particular text manipulation tasks, has its own syntax
Preprocessor directives
memory that is available for your programs to use
RAM (random access memory)
Constant in cstdlib that holds the maximum random number
RAND_MAX
operators that let you compare two values
Relational operators
executes the program until execution reaches the statement selected by your mouse cursor
Run to cursor
constants whose initialization values can only be resolved at runtime
Runtime constants
determines where a variable is accessible
Scope
functions that set the value of a private member variable.
Setters (also sometimes called mutators)
Statement that does not contain expressions, statement that contains expressions, or expression statement? int x;
Statement that does not contain expressions
What is the difference between a statement and an expression?
Statements are used when we want the program to perform an action. Expressions are used when we want the program to calculate a value
tools that analyze your code and look for semantic issues that may indicate problems with your code
Static analysis tools
happens for static and global variables. Memory for these types of variables is allocated once when your program is run and persists throughout the life of your program
Static memory allocation
executes the next statement in the normal execution path of the program, and then pauses execution. If the statement contains a function call, this causes the program to jump to the top of the function being called
Step into
executes all remaining code in the function currently being executed and then returns control to you when the function has returned
Step out
T/F? Const variables must be initialized when you define them, and then that value can not be changed via assignment
T
T/F? Failure to return a value from a function with a non-void return type (other than main) will result in undefined behavior.
T
T/F? When you #include a file, the content of the included file is inserted at the point of inclusion. This provides a useful way to pull in declarations from another file.
T
T/F? You can use nested initializer lists for nested structs
T
T/F? You should call std::rand() once initially to get better random numbers
T
T/F? arrays that are part of structs or classes do not decay when the whole struct or class is passed to a function.
T
T/F? because the void pointer does not know what type of object it is pointing to, it cannot be dereferenced directly! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.
T
T/F? blocks can be nested inside other blocks:
T
T/F? custom types should be passed by const reference.
T
T/F? dynamically allocating an array allows us to choose an array length at runtime
T
T/F? enumerators are placed into the same namespace as the enumeration
T
T/F? expressions are always evaluated as part of statements
T
T/F? std::int8_t and std::uint8_t may behave like chars instead of integers
T
T/F? structs can contain functions
T
T/F? the function body is a block
T
T/F? wchar_t should almost always be avoided
T
T/F? Once declared, a default argument can not be redeclared. That means for a function with a forward declaration and a function definition, the default argument can be declared in either the forward declaration or the function definition, but not both.
T (Best practice is to declare the default argument in the forward declaration and not in the function definition)
T/F? You can use constexpr variables for symbolic constants
T (and recommended)
T/F? This is one way of using symbolic constants #define MAX_STUDENTS_PER_CLASS 30 int max_students { numClassrooms * MAX_STUDENTS_PER_CLASS };
T (but not recommended)
T/F? You can use the define preprocessor directive to create symbolic constant
T (but not recommended)
T/F? Lifetime is a run-time property.
T (note: scope is a compile-time property)
T/F? You can return values, references, or addresses
T1
Type THIS FUNCTION GETS A RANDOM NUMBER int getRandomNumber(int min, int max) { static constexpr double fraction { 1.0 / (RAND_MAX + 1.0) }; return min + static_cast<int>((max - min + 1) * (std::rand() * fraction)); }
THIS FUNCTION GETS A RANDOM NUMBER
operators that act on three operands
Ternary operators
a library that ships with C++. It contains additional functionality to use in your programs.
The C++ Standard Library
provides the fastest signed integer type with a width of at least # bits
The fast type (std::int_fast#_t)
provides the smallest signed integer type with a width of at least # bits
The least type (std::int_least#_t)
What symbol are statements in C++ often ended with?
The semicolon (;)
Just read this and type X If a variable is trivial, then it can have a short name (like i, index, x, count, etc). Otherwise, it should be descriptive. Always avoid abbreviations.
X
Type X #include <iostream> #include <cstddef> // for NULL void print(int x) { std::cout << "print(int): " << x << '\n'; } void print(int *x) { if (!x) std::cout << "print(int*): null\n"; else std::cout << "print(int*): " << *x << '\n'; } int main() { int *x { NULL }; print(x); // calls print(int*) because x has type int* print(0); // calls print(int) because 0 is an integer literal print(NULL); // likely calls print(int), although we probably wanted print(int*) return 0; }
X
Type X #include <iostream> // x is not in scope anywhere in this function void doSomething() { std::cout << "Hello!\n"; } int main() { // x can not be used here because it's not in scope yet int x{ 0 }; // x enters scope here and can now be used doSomething(); return 0; } // x goes out of scope here and can no longer be used
X
Type X 2 // 2 is a literal that evaluates to value 2 "Hello world!" // "Hello world!" is a literal that evaluates to text "Hello world!" x // x is a variable that evaluates to the value of x 2 + 3 // 2 + 3 uses operator + to evaluate to value 5 x = 2 + 3 // 2 + 3 evaluates to value 5, which is then assigned to variable x std::cout << x // x evaluates to the value of x, which is then printed to the console
X
Type X All of the integers (except int) can take an optional int suffix: The integer types can also take an optional signed keyword (typically before the type) Neither of these are recommended Short is 2 bytes usually, int is 4, long is 4, long long is 8
X
Type X Any variable that should not be modifiable after initialization and whose initializer is known at compile-time should be declared as constexpr. Any variable that should not be modifiable after initialization and whose initializer is not known at compile-time should be declared as const.
X
Type X Avoid static local variables unless the variable never needs to be reset. static local variables decrease reusability and make functions harder to reason about
X
Type X Avoid using the comma operator, except within for loops.
X
Type X However, starting with C++11, it's now possible to initialize dynamic arrays using initializer lists!
X
Type X Just like we use "g_" to prefix global variables, it's common to use "s_" to prefix static (static duration) local variables
X
Type X Set deleted pointers to 0 (or nullptr in C++11) unless they are going out of scope immediately afterward.
X
Type X Strongly favor the prefix version of the increment and decrement operators, as they are generally more performant, and you're less likely to run into strange issues with them.
X
Type X This code fixes cin failures if (std::cin.fail()) // has a previous extraction failed or overflowed? { // yep, so let's handle the failure std::cin.clear(); // put us back in 'normal' operation mode std::cin.ignore(32767,'\n'); // and remove the bad input }
X
Type X This is the recommended way to get input for a C-style string #include <iostream> #include <iterator> // for std::size int main() { char name[255]; // declare array large enough to hold 255 characters std::cout << "Enter your name: "; std::cin.getline(name, std::size(name)); std::cout << "You entered: " << name << '\n'; return 0; }
X
Type X When writing a source file, include the corresponding header (If one exists), even if you don't need it yet.
X
Type X When you separate your code into multiple files, you'll have to use a namespace in the header and source file
X
Type X void foo(int x, int y) // Comma used to separate parameters in function definition { add(x, y); // Comma used to separate arguments in function call int z(3), w(5); // Comma used to separate multiple variables being defined on the same line (don't do this) }
X
Are these functions equivalent? Y/N void changeArray(int *ptr) { } void changeArray(int ptr[]) { }
Y
Are these statements equivalent? Y/N int& ref1{ value }; int &ref2{ value };
Y
Can you use scientific notation in floating point literals? Y/N
Y
Do for-each loops work with vectors?
Y
Does copy and direct initialization allow for conversions where data would be lost? Y/N
Y
Is this correct? Y/N std::cout << "Hello\n";
Y
Is this correct? Y/N std::cout << "x is equal to: " << x << '\n';
Y
Is this valid? Y/N void printInteger(const int myValue) { std::cout << myValue; }
Y
Is this valid? Y/N double electron { 1.6e-19 };
Y
Will the two printed lines be the same? Y/N #include <iostream> int main() { int v{ 5 }; int *ptr{ &v }; std::cout << &v << '\n'; std::cout << ptr << '\n'; return 0; }
Y
Will this compile? int main() { int x { 5 }; { ++x; int y { 7 }; } return 0; }
Y
Will this compile? Y/N #include <iostream> #include <string> int main() { std::string firstName{}; std::string lastName{}; std::cout << "First name: "; std::cin >> firstName; std::cout << "Last name: "; std::cin >> lastName; if (std::string fullName{ firstName + ' ' + lastName }; fullName.length() > 20) { std::cout << '"' << fullName << "\"is too long!\n"; } else { std::cout << "Your name is " << fullName << '\n'; } return 0; }
Y
Will this compile? Y/N #include <iostream> int main() { int selection; do { std::cout << "Please make a selection: \n"; std::cout << "1) Addition\n"; std::cout << "2) Subtraction\n"; std::cout << "3) Multiplication\n"; std::cout << "4) Division\n"; std::cin >> selection; } while (selection != 1 && selection != 2 && selection != 3 && selection != 4); std::cout << "You selected option #" << selection << "\n"; return 0; }
Y
Will this compile? Y/N #include <iostream> namespace foo { namespace goo // goo is a namespace inside the foo namespace { int add(int x, int y) { return x + y; } } } int main() { std::cout << foo::goo::add(1, 2) << '\n'; return 0; }
Y
Will this compile? Y/N for (int count{ 0 }; count < 10; ++count) std::cout << count << ' ';
Y
Will this compile? Y/N for (int iii{ 0 }, jjj{ 9 }; iii < 10; ++iii, --jjj) std::cout << iii << ' ' << jjj << '\n';
Y
Will this compile? Y/N int array[2][4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
Y
Will this compile? Y/N int array[][4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
Y
Will this compile? Y/N int array[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
Y
Will this error? Y/N If not what does it print? #include <iostream> int main() { enum class Color { red, blue }; Color color{ Color::blue }; std::cout << color; }
Y
arr[2] *(arr + 2) *(2 + arr) 2[arr] Are these lines of code ALL equivalent? Y/N
Y
Will this error? Y/N #include <iostream> int main() { bool b{ 4 }; std::cout << b; return 0; }
Y (error: narrowing conversions disallowed)
Will this error? #include <iostream> int sumArray(const int array[]) { int sum{ 0 }; for (auto number : array) { sum += number; } return sum; } int main() { constexpr int array[]{ 9, 7, 5, 3, 1 }; std::cout << sumArray(array) << '\n'; return 0; }
Y (for-each does not work with pointer)
Will this work? Y/N This is a pain, particularly for structs with many members. In C++11, you can now assign values to structs members using an initializer list: struct Employee { short id; int age; double wage; }; Employee joe; joe = { 1, 32, 60000.0 };
Y (in C++11 and above)
Will this error? Y/N class DateClass { public: int m_year{}; int m_month{}; int m_day{}; }
Y (semicolon)
Will this compile? Y/N int array[2][5] { { 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 } };
Y (the first array will get another zero)
Will this error? Y/N If so, what line(s) would error? class Something { public: int m_value; Something(): m_value{0} { } void setValue(int value) { m_value = value; } int getValue() { return m_value ; } }; int main() { const Something something{}; //1 something.m_value = 5; //2 something.setValue(5); //3 return 0; }
Y (you can not edit the member variables in any way), 2,3
Will this error? Y/N void printValues(int x, int y=10); void printValues(int x, int y=10) { std::cout << "x: " << x << '\n'; std::cout << "y: " << y << '\n'; }
Y (you can only define a default value once)
Will this compile? Y/N If so, what is animal_dog assigned to? enum Animal { animal_cat = -3, animal_dog, animal_pig, animal_horse = 5, animal_giraffe = 5, animal_chicken };
Y, -2
Will this error? Y/N If so, how would you fix this? Animal animal = 5;
Y, Color color = static_cast<Color>(5);
Does cin fail when a too large number has been inputted?
Yes
Initializing a variable with empty braces indicates (int width{})
Zero initialization
double quote escape sequence
\"
single quote escape sequence
\'
Backslash escape sequence
\\
newline escape sequence
\n
horizontal tab escape sequence
\t
a short public function whose job is to retrieve or change the value of a private member variable
access function
allows us to see what memory address is assigned to a variable
address-of operator (&)
a data type that groups multiple individual variables together
aggregate data type
a struct is an _____________________________________
aggregate data type
When implicit conversion is allowed (such as in copy initialization), what integers will result in a boolean being true?
all except 0
Newlines (are / are not) allowed in quoted text
are
a value that is passed from the caller to the function when a function call is made i.e. doPrint(); // this call has no arguments printValue(6); // 6 is the argument passed to function printValue() add(2, 3); // 2 and 3 are the arguments passed to function add()
argument
The number of operands that an operator takes as input is called the operator's _____________
arity
an aggregate data type that lets us access many variables of the same type through a single identifier
array
std::array is in what header
array
Write an expression that resizes this vector to a length of 5 std::vector array { 0, 1, 2 };
array.resize(5)
Write an expression that gets the size of this vector std::vector array { 9, 7, 5, 3, 1 };
array.size()
with a pointer, you need to use the _______________ to access members of a struct.
arrow operator
A preprocessor macro that evaluates a conditional expression at runtime. If the conditional expression is true, the assert statement does nothing. If the conditional expression evaluates to false, an error message is displayed and the program is terminated
assert statement
the operator's ______________ tells the compiler whether to evaluate the operators from left to right or from right to left
associativity
Rewrite using trailing return syntax. int add(int x, int y) { return (x + y); }
auto add(int x, int y) -> int { return (x + y); }
When initializing a variable, the ___________ keyword can be used in place of the type to tell the compiler to infer the variable's type from the initializer's type. This is called ___________
auto, type inference (also sometimes called type deduction).
Variables with ______________ duration are created at the point of definition, and destroyed when the block they are part of is exited. This includes: Local variables, Function parameters
automatic
returns the value of the top element on the stack of a std::vector
back()
1. Constructors must have the same name as the class (with the same capitalization) 2. Constructors have no return type (not even void) Is 1 true? 2? both? neither? (only write one thing)
both
When the address of variable value is assigned to ptr, which of the following are true: ptr is the same as &value //1 *ptr is treated the same as value //2
both
In the context of a loop, a ______________ can be used to cause the loop to terminate early:
break statement
tells the compiler that we are done with this switch (or while, do while, or for loop)
break statement (declared using the break keyword)
a special marker that tells the debugger to stop execution of the program when the breakpoint is reached.
breakpoint
the verb for starting the execution of a function
call
a list of all the active functions that have been executed to get to the current point of execution.
call stack
a debugger window that shows the call stack.
call stack window
the function being called
callee / called function
The function initiating the function call
caller
global variables (can/cannot) be shadowed
can
Get the capacity of a std::vector using the ______________ function
capacity()
a kind of label is the case label, which is declared using the _________ keyword and followed by a constant expression
case
Define a variable with value '5' and name ch
char ch{'5'}; (or char ch{53};)
What are the four Character types?
char, wchar_t, char16_t, char32_t
a char can be defined as using a ___________________ or an ________________
character literal, integer
What does cout stand for?
character output
allows you to evaluate multiple expressions wherever a single expression is allowed
comma operator (,)
programmer-readable note that is inserted directly into the source code of the program, ignored by the compiler and are for the programmer's use only.
comment
the type of a variable must be known at (compile-time or run-time?)
compile-time
when the program is compiled
compile-time
A declaration is needed to satisfy the (linker/compiler)
compiler
When two (or more) definitions for a function (or global variable) are introduced into the same file (often via an #include), a naming collision error will occur in the (compiler/linker)
compiler
Accessing an identifier out of scope will throw a (run-time/complile-time?) error
complile-time
a group of zero or more statements that is treated by the compiler as if it were a single statement.
compound statement (also called a block, or block statement)
an expression that evaluates to a Boolean value
condition (conditional expression)
Preprocessor directives that allow you to specify under what conditions something will or won't compile
conditional compilation preprocessor directives
a ternary operator that provides a shorthand method for doing a particular type of if/else statement
conditional operator (?:, sometimes referred to as "the ternary operator")
To declare a const pointer, use the __________ keyword between the asterisk and the pointer name
const
To make a variable constant, simply put the ____________________ keyword either before or after the variable type
const
What is the default type of C-style string literals?
const char[]
________________a___________ is a member function that guarantees it will not modify the object or call any non-const member functions (as they may modify the object). To make a ________________a___________ , we simply append the const keyword to the function prototype, after the parameter list, but before the function body:
const member function
a pointer whose value can not be changed after initialization
const pointer
To declare a pointer to a const value, use the ________ keyword (before/after) the data type:
const, before
a fixed value that may not be changed
constant
keyword that ensures that a constant must be a compile-time constant
constexpr
a special kind of class member function that is automatically called when an object of that class is instantiated, typically used to initialize member variables of the class to appropriate default or user-provided values, or to do any setup steps necessary for the class to be used (e.g. open a file or database).
constructor
class IntArray { private: int *m_array{}; int m_length{}; public: IntArray(int length) // this is a ______________ { assert(length > 0); m_array = new int[static_cast<std::size_t>(length)]{}; m_length = length; } ~IntArray() // this is a _______________ { delete[] m_array; } void setValue(int index, int value) { m_array[index] = value; } int getValue(int index) { return m_array[index]; } int getLength() { return m_length; } };
constructor, destructor
The ___________________ provides a convenient way to jump to the end of the loop body for the current iteration. This is useful when we want to terminate the current iteration early.
continue statement
if your conditional is an expression that does not evaluate to a Boolean value, the conditional expression is ____________________
converted to a Boolean value (0 = false, other = true)
giving a variable a value using the = operator.
copy assignment (assignment)
NULL header
cstddef
What library includes fast ints?
cstdint
C++) comes with a built-in pseudo-random number generator. It is implemented as two separate functions that live in the ________ header
cstdlib
std::time(nullptr) requires the _________ header
ctime
A pointer that is pointing to deallocated memory is called a _____________________
dangling pointer
any information that can be moved, processed, or stored by a computer, any sequence of symbols (numbers, letters, etc...) that can be interpreted to mean something
data
tells the compiler how to interpret the contents of memory in some meaningful way
data type
tells the compiler what type of value the variable will store, tells the program how to interpret a value in memory.
data type (type)
a tool that allows the programmer to control how a program executes and examine the program state while the program is running
debugger
The process of finding and removing errors from a program
debugging
en a fixed array is used in an expression, the fixed array will ______ (be implicitly converted) into a pointer that points to the _______ element of the array
decay, first
A _________________________ is a statement that tells the compiler about the existence of an identifier and its type information.
declaration
The second kind of label is the default label (often called the "default case"), which is declared using the _________ keyword
default
a default value provided for a function parameter.
default argument
A constructor that takes no parameters
default constructor
A ______________ actually implements (for functions or types) or instantiates (for variables) the identifier.
definition
a special kind of declaration statement used to create a variable
definition
Constructors are allowed to call other constructors. This process is called ___________________
delegating constructors (or constructor chaining)
Write code that would delete the following dynamically allocated variable. int *ptr2{ new int { 6 } };
delete ptr2; ptr2 = nullptr;
Write code that would delete the following dynamically allocated variable. double *test{ new double{ 6 } };
delete test; test = nullptr;
Write a statement that deallocates the memory in this array int *array{ new int[length]{} };
delete[] array;
allows us to access the value at a particular address
dereference operator (*)
a special kind of class member function that is executed when an object of that class is destroyed
destructor
local variables (do/do not) have linkage
do not
One interesting thing about the while loop is that if the loop condition is initially false, the while loop will not execute at all. It is sometimes the case that we know we want a loop to execute at least once, such as when displaying a menu. To help facilitate this, C++ offers the _____________________ loop
do-while
C++ (does/does not) define the order of evaluation for function arguments or operator operands.
does not
by default, floating point literals default to type (float, double, long double)
double
Declare a null pointer of type double using a keyword named ptr
double *ptr{ nullptr };
Initialize a variable named test that holds a pointer to a dynamically allocated double with the value of 6
double *test{ new double{ 6 } };
how would you initialize a variable named test that would allow you to access a dynamically allocated double
double *test{ new double};
Variables with ___________ duration are created and destroyed by programmer request. This includes: Dynamically allocated variables
dynamic
What does endl stand for?
end line
Enumerations are defined via the ________________ keyword
enum
Write the forward declaration for this enum enum Color { color_black, color_red, };
enum Color : int;
Rewrite this enum to use short integers enum Color { color_black, color_red, };
enum Color : short { color_black, color_red, };
define an enumeration named Directions with the cardinal directions as possible values.
enum Directions { north, south, west, east, };
C++11 defines a new concept, the ____a__________ , which makes enumerations both strongly typed and strongly scoped. To make an __________a___________, we use the keyword ________b________ after the enum keyword
enum class (also called a scoped enumeration), class
data type where every possible value is defined as a symbolic constant
enumerated type (also called an enumeration or enum)
symbolic constants in enums/enumerations are called _________________
enumerators
some characters in C++ that have special meaning, starts with a '\' (backslash) character and then a following letter or number
escape sequences
The process of acting on each of the terms in an expression until a single value remains
evaluation (think evaluating)
offer a mechanism for handling errors that occur in a function. If an error occurs in a function that the function cannot handle, the function can trigger one of these
exceptions
The conditional operator evaluates as a
expression
a combination of literals, variables, operators, and explicit function calls that produce a single output value
expression
Statement that does not contain expressions, statement that contains expressions, or expression statement? std::cout << x;
expression statement
Statement that does not contain expressions, statement that contains expressions, or expression statement? x = 5;
expression statement
a statement that consists of an expression followed by a semicolon, can be meaningless/useless
expression statement
bool b {}; What is the value of b?
false
means they are visible from the point of declaration until the end of the file in which they are declared
file scope
Global variables have ______________
file scope (also informally called global scope or global namespace scope)
integers that are guaranteed to have the same size on any architecture.
fixed-width integers
Initialize a double pointer with a null pointer (wihtout using a keyword) named ptr
float *ptr { 0 };
Define a float variable named xyz with a value of 160 using scientific notation.
float xyz{1.6e2f};
What are the three floating point types?
float, double, long double
a variable type that can hold a real number, such as 4320.0, -3.33, or 0.01226
floating point
Comparing ___________________ can lead to unexpected results (especially with equality or very close numbers)
floating point numbers
Write a for each loop (with no content) that iterates over this array. The variable should be named str and it both should not be able to edit the original array or be a copy of the array's values. std::string array[]{ "peter", "likes", "frozen", "yogurt" };
for (const std::string &str: array) {}
Write a for each loop (with no content) that iterates over this array. The variable should be named num. constexpr int fibonacci[]{ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
for (int num: fibonacci) {}
The ____________________ is ideal when we know exactly how many times we need to iterate, because it lets us easily define, initialize, and change the value of loop variables after each iteration.
for statement (also called a for loop)
This is the syntax for what loop? for (element_declaration : array) statement;
for-each loop
While for loops provide a convenient and flexible way to iterate through an array, they are also easy to mess up and prone to off-by-one errors. There's a simpler and safer type of loop called a _____________ for cases where we want to iterate through every element in an array (or other list-type structure).
for-each loop (also called a range-based for-loop)
In order to call a function defined in another file, you must place a __________________ for the function in any other files wishing to use the function
forward declaration
allows us to tell the compiler about the existence of an identifier before actually defining the identifier (works with functions, variables, and user-defined types, all with different syntax)
forward declaration
To actually use an external global variable that has been defined in another file, you also must place a _______________________ for the global variable in any other files wishing to use the variable. For variables, creating a forward declaration is done via the ________ keyword (with no initialization value).
forward declaration, extern
This code uses what method thing so that add() can be used in main()?, What is the declaration statement in the line commented HERE called? #include <iostream> int add(int x, int y); // HERE int main() { std::cout << "The sum of 3 and 4 is: " << add(3, 4) << '\n'; // this works because we forward declared add() above return 0; } int add(int x, int y) // even though the body of add() isn't defined until here { return x + y; }
forward declaration, function prototype
To use a function from another file you need to ________________________ it
forward declare
A collection of statements that executes sequentially
function
a reusable sequence of statements designed to do a particular job
function
the braces and the statements that make up a function
function body
an expression that tells the CPU to interrupt the current function and execute another function
function call
a variable used in a function that are always initialized with a value provided by the caller of the function void printValue(int x) //one integer parameter named x { std::cout << x << '\n'; }
function parameter
a declaration statement that consists of the function's return type, name, parameters, but no function body
function prototype
C++ comes with built-in support for many different data types called __________________
fundamental data types (basic types, primitive types, or built-in types)
At the library, program, or function level, use comments to describe what. Inside the library, program, or function, use comments to describe how. At the statement level, use comments to describe why.
general rules for commenting
In C++, any name that is not defined inside a class, function, or a namespace is considered to be part of an implicitly defined namespace called the ______________________________
global namespace (global scope)
Global variables have __________ , which means they can be accessed from the point of declaration to the end of the file in which they are declared.
global scope (aka. file scope)
Variables and functions with ___________ / ______________ can be accessed anywhere in the file. This includes: Global variables, Functions, User-defined type definitions (such as enums and classes) declared inside a namespace or in the global scope
global scope, file scope
variables declared outside of a function
global variables
The ___________ is a control flow statement that causes the CPU to jump to another spot in the code. This spot is identified through use of a _________________________.
goto statement
three keywords for jumps
goto, break, continue
used to test whether one value is greater than another
greater than operator (>)
The most basic control flow statement is the ________, which tells the program to quit running immediately
halt
The primary purpose of a ________________is to propagate declarations to code files.
header file
conditional compilation directives that take the following form: #ifndef SOME_UNIQUE_NAME_HERE #define SOME_UNIQUE_NAME_HERE // your declarations (and certain types of definitions) here #endif
header guard (include guard
The statements at the top of a file with a # are _________
headers
What will this output? #include <iostream> int main() { if (4) std::cout << "hi"; else std::cout << "bye"; return 0; }
hi
However, logical AND has (lower/higher) precedence than logical OR
higher
the name that a variable is accessed by., used in an application to access or modify a variable's value.
identifier
The most basic kind of conditional branch in C++
if statement
if (condition) statement; This is the simplest form of a ________________
if statement
you can mimic logical XOR using the
inequality operator (!=)
a while loop where the expression always evaluates to true
infinite loop
What are the three fundamentals of Object oriented programming
inheritance, encapsulation, polymorphism (abstraction maybe too)
If you need a variable in an if-statement, but not outside, you can use an _____________ before the condition.
init-statement
class Something { private: int m_value1; double m_value2; char m_value3; public: Something() : m_value1{ 1 }, m_value2{ 2.2 }, m_value3{ 'c' } // This is called an ___________________ { } void print() { std::cout << "Something(" << m_value1 << ", " << m_value2 << ", " << m_value3 << ")\n"; } }; int main() { Something something{}; something.print(); return 0; }
initialization list
int prime[5]{ 2, 3, 5, 7, 11 }; // uses an ______________ to initialize the fixed array
initializer list
Initializing structs by assigning values member by member is a little cumbersome, so C++ supports a faster way to initialize structs using an _______________________
initializer list.
An ______________ is a namespace that is typically used to version content. Much like an unnamed namespace, anything declared inside an _________________ is considered part of the parent namespace. However, ______________ don't give everything internal linkage. (all same)
inline namespace
When used with cout, << is called the ____________
insertion operator
An instantiated object
instance
What is the default type of integral value literals?
int
Declare a const pointer int named ptr to the pointer of an int named value
int *const ptr = &value;
Zero-Initialize an int with identifier iPtr
int *iPtr{};
Initialize a pointer with identifier ptr to the address of v. int v{ 5 };
int *ptr{ &v };
how would you initialize a variable named test that would allow you to access a dynamically allocated int
int *test{ new int };
Initialize a variable named test that holds a pointer to a dynamically allocated int with the value of 6
int *test{ new int{ 6 } };
Write the function prototype for this function (use the preferred form with names): int doMath(int first, int second, int third, int fourth) { return first + second * third / fourth; }
int doMath(int first, int second, int third, int fourth);
An identifier with ________________ linkage can be accessed anywhere within the file it is declared. This includes: Static global variables (initialized or uninitialized), Static functions, Const global variables, Functions declared inside an unnamed namespace, User-defined type definitions (such as enums and classes) declared inside an unnamed namespace
internal
An identifier with _________________ can be seen and used within a single file, but it is not accessible from other files (that is, it is not exposed to the linker).
internal linkage
Each time a loop executes, it is called an ___________.
iteration
an object designed to traverse through a container (e.g. the values in an array, or the characters in a string), providing access to each element along the way.
iterator
std::size() is in what header
iterator
a ___________ unconditionally causes the CPU to jump to another statement
jump
the set of 84 words the C++ reserves for its own use. They have a special meaning, and identifiers cannot be them.
keywords (reserved words)
What suffixes can you add to an integral value literal to make it long?
l, L
Inside the block of a switch statement, we use ____________ to define all of the values we want to test for equality
labels
It's (legal/illegal) to declare namespace blocks in multiple locations (either across multiple files, or multiple places within the same file)
legal
In the context of a std::vector, _____a____ is how many elements are being used in the array, whereas _____b____ is how many elements were allocated in memory.
length, capacity
used to test whether one value is less than another
less than operator (<)
a collection of precompiled code that has been "packaged up" for reuse in other programs
library file
the time between an object's creation and destruction
lifetime
An identifier's ____________ determines whether other declarations of that name refer to the same object or not
linkage
A definition is needed to satisfy the (linker/compiler)
linker
When two (or more) definitions for a function (or global variable) are introduced into separate files that are compiled into the same program, a naming collision error will occur in the (compiler/linker)
linker
a fixed value that has been inserted directly into the source code, has a value and a type
literal (literal constant)
the two kinds of constants
literal constants, symbolic constants
What suffixes can you add to an integral value literal to make it long long?
ll, LL
Function parameters, as well as variables defined inside the function body
local variables
a file that records events that occur in a program
log file
The process of writing information to a log file
logging
used to test whether both operands are true.
logical AND operator
used to test whether either of two conditions is true
logical OR operator
define a signed long long with the identifier ll
long long ll;
a rule that defines how input text is converted into replacement output text
macro
a literal (usually a number) in the middle of the code that does not have any context.
magic number
What is the name of the function that all programs must have?
main
Functions defined inside of a class are called ____________________
member functions
you can select the member of a struct using the ____________
member selection operator (.):
When we define an instance of a struct, we access the individual members using the __________________
member selection operator (which is a period)
variables that are part of the struct are called _______________________
members (or fields)
This causes a _____________________ int value = 5; int *ptr{ new int{} }; ptr = &value;
memory leak
This causes a _____________________ void doSomething() { int *ptr{ new int{} }; }
memory leak
what happens when we have a variable inside a nested block that has the same name as a variable in an outer block? When this happens, the nested variable "hides" the outer variable in areas where they are both in scope. This is called _____________ or _______________
name hiding, shadowing
a region that allows you to declare names inside of it for the purpose of disambiguation
namespace
Write a statement that aliases the namespace foo::goo to boo
namespace boo = foo::goo;
The scope provided by a namespace
namespace scope
the error when two identical identifiers are introduced into the same program in a way that the compiler or linker can't tell them apart
naming collision (naming conflict)
the _______________ of a function is the maximum number of blocks you can be inside at any point in the function
nesting level (also called the nesting depth)
To allocate a single variable dynamically, we use the scalar (non-array) form of the _________ operator:
new
An identifier with _____________ linkage means the identifier only refers to itself. This includes: Local variables, User-defined type definitions (such as enums and classes) declared inside a block
no
void means
no type
Namespace identifiers are typically (capitalized/non-capitalized)
non-capitalized
when main() returns 0, it indicates that the function ran _____________
normally/successfully
It is possible to omit the statement part of an if statement. A statement with no body is called a _______________
null statement
if (x > 10) ; // this is a _________________
null statement
a special character ('\0', ascii code 0) used to indicate the end of the string
null terminator
a keyword for a null pointer
nullptr
when we convert a value from a larger type to a similar smaller type, or between different types
numeric conversion
Whenever a value from one fundamental data type is converted into a value of a larger fundamental data type from the same family
numeric promotion (or widening, though this term is usually reserved for integers)
a region of storage (usually memory) that has a value and other associated properties (how memory is accessed indirectly), can be named or unnamed/anonymous, excludes functions (at least in C++)
object
the two basic types of macros
object-like macros, function-like macros
pops an element off the stack of a std::vector
pop_back()
The order in which operators are evaluated in a compound expression is determined by an operator's ______________
precedence
a program that finds and attaches to your program the indicated libraries for compilation
preprocessor
class members are (public/private) by default
private
All of the information tracked in a program (variable values, which functions have been called, the current point of execution)
program state
struct members are (public/private) by default
public
declarations that aren't definitions
pure declarations
pushes an element on the stack of a std::vector
push_back()
A ______________________ in C++ is a function that calls itself.
recursive function
A ______________ is a condition that, when met, will cause the recursive function to stop calling itself
recursive termination
Splitting into multiple sub-functions
refactoring
The process of restructuring your code without changing what it actually does
refactoring
a type of C++ variable that acts as an alias to another object or value
reference
void addOne(int &ref) // ref is a ______________ variable { ref = ref + 1; }
reference
Sometimes we need a function to return multiple values. However, functions can only have one return value. One way to return multiple values is using ______________
reference parameters
This where a return value is copied from a called function back to the caller.
return by value
In a function, indicates the specific value being returned to the caller
return statement
You set this to indicate what type of value will be returned from a function.
return type
The specific value returned from a function
return value
When precision is lost because a number can't be stored precisely
rounding error
Type rounding errors make floating point comparisons tricky
rounding errors make floating point comparisons tricky
In a two-dimensional array, it is convenient to think of the first (left) subscript as being the _______ , and the second (right) subscript as being the ______
row, column
When the program is run
runtime
When calculating the result of a pointer arithmetic expression, the compiler always multiplies the integer operand by the size of the object being pointed to. This is called ________
scaling
determines where the identifier can be accessed within the source code
scope
The reason we have to use a scope qualifier to access a enumerator in a class enumeration is because they are strongly _________
scoped
occurs when a statement is syntactically valid, but does not do what the programmer intended
semantic error
when a statement is syntactically valid, but does not do what the programmer intended
semantic error
What is the best practice for naming variables and functions?
snake_case and camelCase
Statement that does not contain expressions, statement that contains expressions, or expression statement? int x = 5;
statement that contains expressions
Using the __________________keyword on a local variable changes its duration from automatic duration to ________________ duration. This means the variable is now created at the start of the program, and destroyed at the end of the program (just like a global variable). As a result, the static variable will retain its value even after it goes out of scope! (one answer, fills both)
static
Variables with _____________ duration are created when the program begins and destroyed when the program ends. This includes: Global variables, Static local variables
static
A type cast that converts between fundamental data types
static cast
Global variables have _______________, which means they are created when the program is started, and destroyed when it ends.
static duration
created when the program starts, and destroyed when it ends
static duration
Variables with static duration are sometimes called ___________
static variables
The____________ operator takes a single value as input, and outputs the same value converted to the type specified inside the angled brackets
static_cast
What operator would you use to do floating point division with integers
static_cast<>
Write an expression statement that casts a character ch into an int
static_cast<int>(ch);
The return value from main is sometimes called a _____________
status code
provides fixed array functionality that won't decay when passed into a function
std::array
declare an std::array of length 5, type double, and name bob with values 1,2,3,4,5
std::array<double, 5> bob { 1, 2, 3, 4, 5 };
returns an iterator (pointer) to the first element of an array
std::begin()
What variable reads input from keyboard? (with namespace)
std::cin
expression that returns whether cin has failed
std::cin.fail() (should be followed by std::cin.clear() and std::cin.ignore(32767,'\n') )
What function can be used to remove a newline from the cin input stream?
std::cin.ignore() (with 32767 and '\n' as arguments)
Using an explicit namespace qualifier, how would you access cout?
std::cout
What variable allows us to send data to the console to be printed as text? (with namespace)
std::cout
Write a statement that prints the value of this pointer int *ptr{ &value };
std::cout << *ptr;
Write a statement that prints the age using the ptr variable. struct Person { int age{}; double weight{}; }; Person person{}; // Member selection using pointer to struct Person *ptr{ &person };
std::cout << ptr->age;
Write a statement that prints the pointer int *ptr{ &value };
std::cout << ptr;
write a statment that will make any following cout print bools as true and false
std::cout << std::boolalpha;
write a statment that will make any following cout print bools as 1 and 0
std::cout << std::noboolalpha;
Write a line of code that sets the precision of std::cout to 5 (assume everything necessary has been imported)
std::cout << std::setprecision(5);
Use ____________ to make cout print in decimal
std::dec
_______a______ returns an iterator to the element of an array that would be one after the last. The iterator returned by _____a_____ is only used as a marker, accessing it causes undefined behavior, because it doesn't point to a real element.
std::end()
What prints a newline character to the console (when used with std::cout)? (with namespace)
std::endl
a halt can be accomplished through use of the _________ function that is defined in the ___________ header
std::exit(), cstdlib
To read a full line of input into a string, use the function___________. (with namespace)
std::getline()
what statement would you write if you wanted to get a name from the console and put it into the the string type variable name?
std::getline(std::cin, name);
Use ____________ to make cout print in hexadecimal
std::hex
Define a fixed-width signed integer of 16-bytes with the name i and value 5.
std::int16_t i{5};
What is the one Null Pointer type?
std::nullptr_t
Use ____________ to make cout print in octal
std::oct
How do you do exponents in c++? (with what function/operator)
std::pow()
Write 3 to the power of 4 as an expression statement
std::pow(3.0, 4.0);
generates the next random number in the sequence. That number will be a pseudo-random integer between 0 and RAND_MAX, a constant in cstdlib that is typically set to 32767
std::rand()
We can override the default precision that std::cout shows by using the ____________________________________ function that is defined in the _____________________ header
std::setprecision(), iomanip
What function can be used to determine the length of an arrray? What library is it from?
std::size(), iterator
sizeof(int) will return a value of what type
std::size_t (unsigned btw)
sets the initial seed value to a value that is passed in by the caller(for random numbers), should only be called once at the beginning of your program, from the cstdlib header
std::srand()
Write the statement that seeds random numbers based off of the clock; (requires ctime header)
std::srand(static_cast<unsigned_int>(std::time(nullptr)));
Define a fixed-width unsigned integer of 64-bytes with the name i and value 5.
std::uint64_t i{5};
provides dynamic array functionality that handles its own memory management.
std::vector (vector header)
declare a vector with name array and type std::string (no definition)
std::vector<std::string> array;
we declare our struct using the _________________ keyword
struct
allows us to group variables of mixed data types together into a single unit.
struct (short for structure)
to access individual elements of an array, we use the array name, along with the _____________________, and a parameter called a ____________ (or _______________) that tells the compiler which element we want. This process is called ________________ or ____________ the array.
subscript operator ([]), subscript, index, subscripting, indexing
Because doing if-else chains on a single variable testing for equality is so common, C++ provides an alternative conditional branching operator called a ______________
switch
We start a switch statement by using the ________ keyword, followed by the expression that we would like to evaluate (in parentheses)
switch
a constant literal value
symbolic constant
Magic numbers should usually be replaced by ____________________
symbolic constants (const variables)
a compiler error that occurs at compile-time when your program violates the grammar rules of the C++ language
syntax error
an error that occurs when you write a statement that is not valid according to the grammar of the C++ language. The compiler will catch these.
syntax error
the single value from evaluating an expression
the result of the expression
a hidden const pointer that holds the address of the object the member function was called on.
this pointer
The auto keyword can also be used to declare functions using a _________________, where the return type is specified after the rest of the function prototype.
trailing return syntax
header files that the a header file you add to your code include
transitive includes
help address these issues, an improved syntax for typedefs has been introduced that mimics the way variables are declared. This syntax is called a ____________
type alias
creates a value of one type from a value of another type
type cast
The process of converting a value from one data type to another
type conversion
alias double to distance_t using typedef
typedef double distance_t;
alias double to count_t using typedef
typedef int count_t;
What suffixes can you add to an integral value literal to make it unsigned?
u, U
returns the operand multiplied by -1.
unary minus
operators that act on one operand
unary operators
returns the value of the operand
unary plus
What are the unary arithmetic operators?
unary plus (+), unary minus (-)
char16_t and char32_t are almost exclusively used for ____________
unicode
Direct initialization is also called
uniform initialization
A variable that has not been given a known value
uninitialized variable
implicitly treat all contents of the namespace as if it had internal linkage, but puts as member of parent namespace
unnamed namespaces
Define an unsigned long named ul;
unsigned long ul;
C++ contains capabilities that allow programmers to create their own data types. These data types are called ________________________
user-defined data types
Functions that you write yourself
user-defined functions
Namespaces that you create for your own declarations are called ________________________
user-defined namespaces
alias int to count_t using type alias
using count_t = int;
typedef int count_t; Rewrite this as a type alias.
using count_t = int;
using std::cout; this is an example of a _________
using declaration statement
tells the compiler to check a specified namespace when trying to resolve an identifier that has no namespace prefix
using directive
using namespace std; is an example of a ______________
using directive
using namespace std; this is an example of a _________
using directive statement
typedef double distance_t; Rewrite this as a type alias.
using distance_t = double;
//WHAT LINE SHOULD BE HERE cout << "Hello World!"; int x{}; cin >> x;
using namespace std;
//WHAT LINE SHOULD BE HERE cout << "Hello World!"; int x{}; std::cin >> x;
using std::cout; (using declaration)
A single piece of data, stored in memory somewhere
value
A named object/a named region of memory
variable
Write a forward declaration for a function named hello. The function should take in an array of 4 ints that is named bob. The array should not decay to a pointer. The function should return no value.
void hello(int (&bob)[4]);