### Visual Studio Build Output Source: https://www.learncpp.com/cpp-tutorial/compiling-your-first-program This is an example of the output window in Visual Studio after a successful build. It indicates that the compilation process has started, compiled the specified file, and successfully created the executable. This output confirms that your code has been compiled without errors. ```text 1>------ Build started: Project: HelloWorld, Configuration: Debug Win32 ------ 1>HelloWorld.cpp 1>HelloWorld.vcxproj -> c:\users\alex\documents\visual studio 2017\Projects\HelloWorld\Debug\HelloWorld.exe ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== ``` -------------------------------- ### C++ Fixing Program with User Input and Function Call Source: https://www.learncpp.com/cpp-tutorial/introduction-to-function-parameters-and-arguments Illustrates how to fix a program by using a function to get user input and another function to process that input. This example shows the typical flow of getting data, passing it to a function, and performing an action with it. ```cpp #include int getValueFromUser() { std::cout << "Enter an integer: "; int input{}; std::cin >> input; return input; } void printDouble(int value) // This function now has an integer parameter { std::cout << value << " doubled is: " << value * 2 << '\n'; } int main() { int num { getValueFromUser() }; printDouble(num); return 0; } ``` -------------------------------- ### C++ Resource Allocation Example Source: https://www.learncpp.com/cpp-tutorial/introduction-to-smart-pointers-move-semantics Illustrates the direct initialization of a resource pointer using `new`. This comment questions the consistency of using direct initialization over list initialization in the context of a learning chapter. ```cpp resource * ptr = new resource (); ``` -------------------------------- ### C++ String Erase Functionality Example Source: https://www.learncpp.com/cpp-tutorial/using-a-language-reference Demonstrates how to remove a portion of a std::string using the erase member function. The example shows removing characters starting from a specific index for a given count. ```cpp #include #include int main() { std::string str{ "The rice is cooking" }; str.erase(4, 11); std::cout << str << '\n'; return 0; } ``` -------------------------------- ### C++ Program for Comparison Source: https://www.learncpp.com/cpp-tutorial/introduction-to-testing-your-code A C++ program that takes two integer inputs from the user and compares them, printing the result. This example is used to illustrate the challenge of testing all possible input combinations. ```cpp #include void compare(int x, int y) { if (x > y) std::cout << x << " is greater than " << y << '\n'; // case 1 else if (x < y) std::cout << x << " is less than " << y << '\n'; // case 2 else std::cout << x << " is equal to " << y << '\n'; // case 3 } int main() { std::cout << "Enter a number: "; int x{}; std::cin >> x; std::cout << "Enter another number: "; int y{}; std::cin >> y; compare(x, y); return 0; } ``` -------------------------------- ### C++ Value-Returning Function Example Source: https://www.learncpp.com/author/Alex/page/12 Demonstrates a value-returning function in C++. This type of function computes a value and returns it to the caller. The example includes getting input from the user and performing a calculation. ```cpp #include int main() { // get a value from the user std::cout << "Enter an integer: "; int num{}; std::cin >> num; // print the value doubled std::cout << num << " doubled is: " << num * 2 << '\n'; return 0; } ``` -------------------------------- ### C++ String View Length Example Source: https://www.learncpp.com/cpp-tutorial/the-benefits-of-data-hiding-encapsulation Demonstrates the use of `std::string_view` and its `length()` member function to get the length of a string literal without exposing the internal implementation details. This showcases a basic example of how encapsulation hides implementation complexity. ```cpp #include #include int main() { std::string_view sv{ "Hello, world!" }; std::cout << sv.length(); return 0; } ``` -------------------------------- ### C++ Main Game Loop and Setup Source: https://www.learncpp.com/cpp-tutorial/chapter-9-summary-and-quiz The main function sets up the game parameters (min, max, tries) and runs the game loop, allowing the user to play multiple rounds. ```cpp #include "hi_lo.h" #include "output.h" int main() { constexpr int min {1}; constexpr int max {100}; constexpr int tries {7}; do { play_hilo(min, max, tries); } while(wants_to_replay()); print_end(); return 0; } ``` -------------------------------- ### C++ Main Function Example Source: https://www.learncpp.com/cpp-tutorial/chapter-6-summary-and-quiz The `main` function demonstrates the usage of `getQuantityPhrase` and `getApplesPluralized`. It first shows an example with a hardcoded value and then prompts the user for input to display personalized apple counts. Requires `` for input/output. ```C++ int main() { constexpr int maryApples{3}; std::cout << "Mary has " << getQuantityPhrase(maryApples) << ' ' << getApplesPluralized(maryApples) << ".\n"; std::cout << "How many apples do you have? "; int numApples{}; std::cin >> numApples; std::cout << "You have " << getQuantityPhrase(numApples) << ' ' << getApplesPluralized(numApples) << ".\n"; return 0; } ``` -------------------------------- ### C++ Variable Naming Conventions and Examples Source: https://www.learncpp.com/cpp-tutorial/keywords-and-naming-identifiers Illustrates various C++ variable naming conventions, including conventional (lowercase, descriptive), unconventional (starting with underscore, all caps for single words, starting with lowercase for multi-word), and invalid (containing spaces, keywords, starting with numbers). This snippet highlights best practices for creating clear and compilable variable names. ```cpp int sum {}; // Conventional int _apples {}; // Unconventional int VALUE {}; // Unconventional // int my variable name {}; // Invalid int TotalCustomers {}; // Unconventional // int void {}; // Invalid int numFruit {}; // Conventional // int 3some {}; // Invalid int meters_of_pipe {}; // Conventional ``` ```cpp //bulabildiğim en kötü isim int _BuBirTAMSAYItUtAnDeğişkenAdınınGereksizUZATILMIŞveSAÇMACABüyükharfkullanılmışHalidir__; //buda hoş bikaç değişken int deveYöntemi; char yılan_yöntemi; int karakterKonumu; ``` -------------------------------- ### std::vector Initialization Examples (C++) Source: https://www.learncpp.com/cpp-tutorial/introduction-to-stdvector-and-list-constructors Demonstrates various ways to initialize std::vector objects using list initialization, default initialization, and copy initialization. It highlights how C++ interprets different syntaxes like {} and initializer lists, influencing constructor selection. ```cpp #include int main() { std::vector v5({ 10 }); // { 10 } interpreted as initializer list, matches list constructor // Default init std::vector v6 {}; // {} is empty initializer list, matches default constructor std::vector v7 = {}; // {} is empty initializer list, matches default constructor return 0; } ``` -------------------------------- ### C++ Function Naming Conventions (Case and Style) Source: https://www.learncpp.com/cpp-tutorial/keywords-and-naming-identifiers Illustrates conventional C++ function naming, emphasizing the preference for starting with a lowercase letter, similar to variables. It shows examples of snake_case and camelCase for multi-word function names and notes the unsuitability of names starting with uppercase letters. ```C++ int my_function_name(); // conventional (separated by underscores/snake_case) int myFunctionName(); // conventional (intercapped/camelCase) int MyFunctionName(); // unconventional (should start with lower case letter) ``` -------------------------------- ### C++ CTAD with Triad Struct and Deduction Guide Source: https://www.learncpp.com/cpp-tutorial/chapter-13-summary-and-quiz Demonstrates Class Template Argument Deduction (CTAD) in C++ for a `Triad` struct. This example shows how CTAD can deduce template arguments automatically, requiring a deduction guide for C++17 compatibility. It includes a `print` function to display the `Triad` contents. ```cpp #include template struct Triad { T first {}; T second {}; T third {}; }; // If using C++17, we need to provide a deduction guide (not required in C++20) // A Triad with three arguments of the same type should deduce to a Triad template Triad(T, T, T) -> Triad; template void print(const Triad& t) { std::cout << '[' << t.first << ", " << t.second << ", " << t.third << ']'; } int main() { Triad t1{ 1, 2, 3 }; print(t1); Triad t2{ 1.2, 3.4, 5.6 }; print(t2); return 0; } ``` -------------------------------- ### C++ Arrays (Part II) - Initialization and Elements Source: https://www.learncpp.com/category/cpp-tutorial/page/31 Continues the discussion on C++ arrays, focusing on initialization methods for fixed-size arrays and how array elements are treated as regular variables. This lesson likely covers accessing elements, assignment, and basic array manipulation. ```cpp #include int main() { // Initializing a fixed-size array int scores[3] = {95, 88, 72}; std::cout << "Score 1: " << scores[0] << std::endl; std::cout << "Score 2: " << scores[1] << std::endl; std::cout << "Score 3: " << scores[2] << std::endl; // Modifying an element scores[1] = 90; std::cout << "Updated Score 2: " << scores[1] << std::endl; return 0; } ``` -------------------------------- ### Code::Blocks Build Output Example (C++) Source: https://www.learncpp.com/cpp-tutorial/compiling-your-first-program Example build log output from Code::Blocks using the GNU GCC Compiler. It shows the compilation and linking commands for a C++ project, indicating a successful build with zero errors and warnings. The output confirms the creation of an executable file. ```text -------------- Build: Debug in HelloWorld (compiler: GNU GCC Compiler)--------------- mingw32-g++.exe -Wall -fexceptions -g -std=c++14 -c C:\CBProjects\HelloWorld\main.cpp -o obj\Debug\main.o mingw32-g++.exe -o bin\Debug\HelloWorld.exe obj\Debug\main.o Output file is bin\Debug\HelloWorld.exe with size 1.51 MB Process terminated with status 0 (0 minute(s), 0 second(s)) 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ``` -------------------------------- ### Stack Push and Pop Sequence Example Source: https://www.learncpp.com/cpp-tutorial/the-stack-and-the-heap Demonstrates the step-by-step process of pushing items onto and popping items off a stack, showing how the stack's contents change with each operation. This is a conceptual illustration of LIFO behavior. ```text Stack: empty Push 1 Stack: 1 Push 2 Stack: 1 2 Push 3 Stack: 1 2 3 Pop Stack: 1 2 Pop Stack: 1 ``` -------------------------------- ### Handle Newlines with cin.get() in C++ Source: https://www.learncpp.com/cpp-tutorial/input-with-istream Illustrates a potential issue with `std::cin.get()` where it stops at a newline character. If the input stream contains a newline after the first read, subsequent `get()` calls might terminate immediately, leading to unexpected behavior as shown in the example. ```cpp int main() { char strBuf[11]{}; // Read up to 10 characters std::cin.get(strBuf, 11); std::cout << strBuf << '\n'; // Read up to 10 more characters std::cin.get(strBuf, 11); std::cout << strBuf << '\n'; return 0; } ``` -------------------------------- ### C++ Class Template for a Pair Source: https://www.learncpp.com/cpp-tutorial/class-templates-with-member-functions An example of a C++ class template named `Pair` that can hold two elements of the same type `T`. It includes a deduction guide for C++17 and older to help with type inference. The example shows how to instantiate `Pair` with different types like `int` and `double`. ```cpp #include template struct Pair { T first{}; T second{}; }; // Here's a deduction guide for our Pair (required in C++17 or older) // Pair objects initialized with arguments of type T and T should deduce to Pair template Pair(T, T) -> Pair; int main() { Pair p1{ 5, 6 }; // instantiates Pair and creates object p1 std::cout << p1.first << ' ' << p1.second << '\n'; Pair p2{ 1.2, 3.4 }; // instantiates Pair and creates object p2 std::cout << p2.first << ' ' << p2.second << '\n'; Pair p3{ 7.8, 9.0 }; // creates object p3 using prior definition for Pair std::cout << p2.first << ' ' << p2.second << '\n'; return 0; } ``` -------------------------------- ### Basic 'Hello, world!' C++ Code Source: https://www.learncpp.com/cpp-tutorial/compiling-your-first-program This is the fundamental C++ code for a 'Hello, world!' program. It includes the necessary header for input/output operations and a main function that prints the message to the console. This code is intended to be used within a Visual Studio project. ```cpp #include int main() { std::cout << "Hello, world!"; return 0; } ``` -------------------------------- ### Instantiating a Base Class Object in C++ Source: https://www.learncpp.com/cpp-tutorial/constructors-and-initialization-of-derived-classes Demonstrates how to create an instance of the Base class using its constructor. This example shows the straightforward instantiation process for a non-derived class. ```cpp int main() { Base base{ 5 }; // use Base(int) constructor return 0; } ``` -------------------------------- ### C++ Class Template Argument Deduction with R3 Struct Source: https://www.learncpp.com/cpp-tutorial/class-template-argument-deduction-ctad-and-deduction-guides Illustrates C++ class template argument deduction (CTAD) with an 'R3' struct. The example shows that omitting the template type arguments in the instantiation of 'R3' requires a deduction guide, as demonstrated in the provided comments. ```cpp #include template struct R3 { T x{}; T y{}; T z{}; }; template R3(T) -> R3; template void printR3(R3 u) { std::cout << '(' << u.x << ", " << u.y << ", " << u.z << ")\n"; } int main() { R3 u{ 1, 2, 3 }; // program stops working when I omit the printR3(u); return 0; } ``` -------------------------------- ### C++ Storage8 Class Template with Bit Manipulation Source: https://www.learncpp.com/cpp-tutorial/class-template-specialization Demonstrates a C++ template class 'Storage8' for efficient storage of 8 bits using bitwise operations. It supports setting and getting individual bits within an integer. Includes an example of its usage with integers and booleans, highlighting template instantiation. ```cpp #include template class Storage8 { private: unsigned char m_data{}; public: // Default constructor initializes m_data to 0 Storage8() = default; // Set the value of a specific bit void set(int index, T value) { // Create a mask for the bit at the given index auto mask{ 1 << index }; // If the value is to be set (true or non-zero) if (value) { // use bitwise-or to turn that bit on m_data |= mask; } else // if we're turning a bit off m_data &= ~mask; // bitwise-and the inverse mask to turn that bit off } bool get(int index) { // Figure out which bit we're getting auto mask{ 1 << index }; // bitwise-and to get the value of the bit we're interested in // Then implicit cast to boolean return (m_data & mask); } }; // Same example as before int main() { // Define a Storage8 for integers (instantiates Storage8, where T = int) Storage8 intStorage; for (int count{ 0 }; count < 8; ++count) { intStorage.set(count, count); } for (int count{ 0 }; count < 8; ++count) { std::cout << intStorage.get(count) << '\n'; } // Define a Storage8 for bool (instantiates Storage8 specialization) Storage8 boolStorage; for (int count{ 0 }; count < 8; ++count) { boolStorage.set(count, count & 3); } std::cout << std::boolalpha; for (int count{ 0 }; count < 8; ++count) { std::cout << boolStorage.get(count) << '\n'; } return 0; } ``` -------------------------------- ### C++ Character Output Source: https://www.learncpp.com/author/Alex/page/36 Provides an example of how to output character data, specifically used here to prompt user input with a question. ```cpp #include int main() { std::cout << "Would you like a burrito? (y/n)"; // We want … ``` -------------------------------- ### File Reading with Return Code Error Checking (C++) Source: https://www.learncpp.com/cpp-tutorial/151-the-need-for-exceptions This C++ code snippet demonstrates reading parameters from a configuration file ('setup.ini'). It includes explicit error checks after each file operation (opening the file, reading integers, doubles, and floats), returning specific error codes. This highlights the verbosity and potential for missed checks when dealing with multiple error conditions using return codes. ```cpp std::ifstream setupIni { "setup.ini" }; // open setup.ini for reading // If the file couldn't be opened (e.g. because it was missing) return some error enum if (!setupIni) return ERROR_OPENING_FILE; // Now read a bunch of values from a file if (!readIntegerFromFile(setupIni, m_firstParameter)) // try to read an integer from the file return ERROR_READING_VALUE; // Return enum value indicating value couldn't be read if (!readDoubleFromFile(setupIni, m_secondParameter)) // try to read a double from the file return ERROR_READING_VALUE; if (!readFloatFromFile(setupIni, m_thirdParameter)) // try to read a float from the file return ERROR_READING_VALUE; ``` -------------------------------- ### Main Game Entry Point in C++ Source: https://www.learncpp.com/cpp-tutorial/chapter-17-summary-and-quiz The main function that starts the Blackjack game. It calls `playBlackjack()` to get the game result and prints the outcome to the console. ```C++ int main() { switch (playBlackjack()) { case GameResult::playerWon: std::cout << "You win!\n"; return 0; case GameResult::dealerWon: std::cout << "You lose!\n"; return 0; case GameResult::tie: std::cout << "It's a tie.\n"; return 0; } return 0; } ``` -------------------------------- ### C++ For Loop Decrementing a Counter Source: https://www.learncpp.com/cpp-tutorial/for-statements An example of a C++ for loop that decrements its counter variable. This loop starts at 9 and iterates down to 0, printing each number followed by a space. It demonstrates the flexibility of the for loop's increment/decrement expression. ```cpp #include int main() { for (int i{ 9 }; i >= 0; --i) std::cout << i << ' '; std::cout << '\n'; return 0; } ``` -------------------------------- ### C++ Input Buffering Example with std::cin Source: https://www.learncpp.com/cpp-tutorial/introduction-to-iostream-cout-cin-and-endl Demonstrates how std::cin handles user input by reading two integers. It illustrates the buffering behavior, where input can be entered all at once or in separate steps. ```cpp #include // for std::cout and std::cin int main() { std::cout << "Enter two numbers: "; int x{}; std::cin >> x; int y{}; std::cin >> y; std::cout << "You entered " << x << " and " << y << '\n'; return 0; } ``` -------------------------------- ### C++ Program Example: Hello World with C-style String Literal Source: https://www.learncpp.com/cpp-tutorial/introduction-to-stdstring Demonstrates the basic structure of a C++ program using `std::cout` to print a C-style string literal. This is a fundamental example for beginners. ```cpp #include int main() { std::cout << "Hello, world!"; // "Hello world!" is a C-style string literal. return 0; } ``` -------------------------------- ### C++ Dereference Operator and Variable Addresses Source: https://www.learncpp.com/cpp-tutorial/introduction-to-pointers Demonstrates using the dereference operator (*) to access the value at a memory address and the address-of operator (&) to get a variable's address. Includes basic C++ I/O setup. ```cpp #include int main() { int x{ 5 }; std::cout << x << '\n'; // print the value of variable x std::cout << &x << '\n'; // print the memory address of variable x std::cout << *(&x) << '\n'; // print the value at the memory address of variable x (parentheses not required, but make it easier to read) return 0; } ``` -------------------------------- ### C++ Static Local Variable Example Source: https://www.learncpp.com/cpp-tutorial/static-local-variables Illustrates a local variable with static duration using the 'static' keyword. The variable is initialized only once at program start and retains its value across function calls. It is not destroyed when the function exits. ```cpp #include void incrementAndPrint() { static int s_value{ 1 }; // static duration via static keyword. This initializer is only executed once. ++s_value; std::cout << s_value << '\n'; } // s_value is not destroyed here, but becomes inaccessible because it goes out of scope int main() { incrementAndPrint(); incrementAndPrint(); incrementAndPrint(); return 0; } ``` -------------------------------- ### C++ Code Snippet - Before Syntax Highlighting Source: https://www.learncpp.com/site-news/learncppcom-tutorials-now-with-syntax-highlighting This snippet demonstrates a C++ code example as it appeared in LearnCpp.com tutorials before the implementation of syntax highlighting and line numbering. It shows a typical assignment operator implementation for a Cents class. ```cpp Cents& Cents::operator= (const Cents &cSource) { // check for self-assignment by comparing the address of the // implicit object and the parameter if (this == &cSource) return *this; // do the copy m_nCents = cSource.m_nCents; // return the existing object return *this; } ``` -------------------------------- ### C++: Combined Solutions for Vector Quiz Questions Source: https://www.learncpp.com/cpp-tutorial/introduction-to-stdvector-and-list-constructors Consolidates solutions for several std::vector quiz questions in a single C++ program. It includes examples for initializing vectors with specific values, defining vectors for a fixed size, and a program to calculate the sum and product of three user-entered integers. ```cpp #include #include int main() { // Question 1: std::vector v{1, 4, 9, 16, 25}; // Question 3: std::vector temps(365); // Question 4: std::vector val(3); std::cout << "Enter 3 integers: "; std::cin >> val[0] >> val[1] >> val[2]; std::cout << "The sum is: " << val[0] + val[1] + val[2] << '\n'; std::cout << "The product is: " << val[0] * val[1] * val[2] << '\n'; return 0; } ``` -------------------------------- ### C++ Example Usage of Timer Class Source: https://www.learncpp.com/cpp-tutorial/timing-your-code Demonstrates how to instantiate and use the Timer class in a C++ program. The timer is started at the beginning of main, and the elapsed time is printed at the end. This is a basic template for timing any part of your C++ code. ```cpp #include int main() { Timer t; // Code to time goes here std::cout << "Time elapsed: " << t.elapsed() << " seconds\n"; return 0; } ``` -------------------------------- ### Getting User Input with a Return Value Function in C++ Source: https://www.learncpp.com/cpp-tutorial/function-return-values-value-returning-functions This C++ example demonstrates a function that retrieves an integer from the user and returns it. The main function then uses this returned value to perform a calculation and display the result. ```cpp #include int getValueFromUser() { std::cout << "Enter an integer: "; int input{}; std::cin >> input; return input; // return the value the user entered back to the caller } int main() { int num { getValueFromUser() }; // initialize num with the return value of getValueFromUser() std::cout << num << " doubled is: " << num * 2 << '\n'; return 0; } ``` -------------------------------- ### Code Formatting for Readability in C++ Source: https://www.learncpp.com/cpp-tutorial/whitespace-and-basic-formatting Provides examples of how to use whitespace effectively to format C++ code for improved readability. Contrasts unformatted, moderately formatted, and well-formatted code. ```cpp #include int main(){std::cout<<"Hello world";return 0;} ``` ```cpp #include int main() { std::cout << "Hello world"; return 0; } ``` ```cpp #include int main() { std::cout << "Hello world"; return 0; } ``` -------------------------------- ### Function Templates with Modifiable Static Local Variables in C++ Source: https://www.learncpp.com/cpp-tutorial/function-template-instantiation Shows how modifiable static local variables within function templates behave. Each instantiation of the template gets its own independent version of the static local variable, leading to separate counts. ```cpp #include // Here's a function template with a static local variable that is modified template void printIDAndValue(T value) { static int id{ 0 }; std::cout << ++id << ") " << value << '\n'; } int main() { printIDAndValue(12); printIDAndValue(13); printIDAndValue(14.5); return 0; } ``` -------------------------------- ### C++ Fraction Class with Inline Input and Methods Source: https://www.learncpp.com/cpp-tutorial/chapter-14-summary-and-quiz Presents an alternative implementation of the Fraction class where the default constructor handles user input for numerator and denominator. This version also integrates the multiply and printFraction logic as member functions of the class. ```cpp #include class Fraction { private: int m_numerator{ 0 }; int m_denominator{ 1 }; public: Fraction(){ std::cout << "Enter a value for numerator: "; std::cin >> m_numerator; std::cout << "Enter a value for denominator: "; std::cin >> m_denominator; std::cout << '\n'; } Fraction(int n, int d) : m_numerator {n}, m_denominator {d} {} Fraction multiply(const Fraction& f2) const { return Fraction{ m_numerator * f2.m_numerator, m_denominator * f2.m_denominator }; } void printFraction() const { std::cout << m_numerator << '/' << m_denominator << '\n'; } }; int main() { Fraction f1{ }; Fraction f2{ }; std::cout << "Your fractions multiplied together: "; f1.multiply(f2).printFraction(); return 0; } ``` -------------------------------- ### C++ Switch Statement with Case Labels and Return Source: https://www.learncpp.com/cpp-tutorial/switch-statement-basics Demonstrates a C++ switch statement where the conditional expression matches a case label. Execution starts at the matching case and uses return statements to exit the function. This example showcases basic switch functionality. ```cpp #include void printDigitName(int x) { switch (x) // x is evaluated to produce value 2 { case 1: std::cout << "One"; return; case 2: // which matches the case statement here std::cout << "Two"; // so execution starts here return; // and then we return to the caller case 3: std::cout << "Three"; return; default: std::cout << "Unknown"; return; } } int main() { printDigitName(2); std::cout << '\n'; return 0; } ``` -------------------------------- ### C++ FixedPoint2: Main Function Demonstration Source: https://www.learncpp.com/cpp-tutorial/chapter-21-summary-and-quiz The main function demonstrates the usage of the FixedPoint2 class, including equality comparisons, addition operations with various sign combinations and potential overflows, type casting to double, and input/output operations using overloaded stream operators. ```cpp int main() { assert(FixedPoint2{ 0.75 } == FixedPoint2{ 0.75 }); // Test equality true assert(!(FixedPoint2{ 0.75 } == FixedPoint2{ 0.76 })); // Test equality false // Test additional cases -- h/t to reader Sharjeel Safdar for these test cases assert(FixedPoint2{ 0.75 } + FixedPoint2{ 1.23 } == FixedPoint2{ 1.98 }); // both positive, no decimal overflow assert(FixedPoint2{ 0.75 } + FixedPoint2{ 1.50 } == FixedPoint2{ 2.25 }); // both positive, with decimal overflow assert(FixedPoint2{ -0.75 } + FixedPoint2{ -1.23 } == FixedPoint2{ -1.98 }); // both negative, no decimal overflow assert(FixedPoint2{ -0.75 } + FixedPoint2{ -1.50 } == FixedPoint2{ -2.25 }); // both negative, with decimal overflow assert(FixedPoint2{ 0.75 } + FixedPoint2{ -1.23 } == FixedPoint2{ -0.48 }); // second negative, no decimal overflow assert(FixedPoint2{ 0.75 } + FixedPoint2{ -1.50 } == FixedPoint2{ -0.75 }); // second negative, possible decimal overflow assert(FixedPoint2{ -0.75 } + FixedPoint2{ 1.23 } == FixedPoint2{ 0.48 }); // first negative, no decimal overflow assert(FixedPoint2{ -0.75 } + FixedPoint2{ 1.50 } == FixedPoint2{ 0.75 }); // first negative, possible decimal overflow FixedPoint2 a{ -0.48 }; assert(static_cast(a) == -0.48); assert(static_cast(-a) == 0.48); std::cout << "Enter a number: "; // enter 5.678 -> 5.68 std::cin >> a; std::cout << "You entered: " << a << '\n'; assert(static_cast(a) == 5.68); return 0; } ``` -------------------------------- ### C++ Constexpr Initializer for Static Variables Source: https://www.learncpp.com/cpp-tutorial/static-local-variables Discusses the implications of `constexpr` initializers for static variables. If a static variable has a `constexpr` initializer, it is guaranteed to be initialized at program start. This example highlights a potential point of confusion regarding `constexpr` and static variables. ```cpp static int s_value = 1; // Assuming s_value has a constexpr initializer ``` -------------------------------- ### C++ Integer Summation with Separate Files (io.cpp and main.cpp) Source: https://www.learncpp.com/cpp-tutorial/chapter-2-summary-and-quiz This C++ example demonstrates organizing code into separate files for implementation (io.cpp) and main logic (main.cpp). The io.cpp file contains functions to read an integer and write the sum of two integers, while main.cpp includes forward declarations and calls these functions. This structure promotes modularity. ```C++ #include int readNumber() { int x; std::cin >> x; //takes an input from user and stores it in var x return x; } void writeAnswer(int x, int y) { std::cout << \"The sum of your entered integers = \" << x + y << \'\\n\'; //stores two int vars and produce their sum } ``` ```C++ #include int readNumber(); void writeAnswer(int x, int y); int main() { std::cout << \"Enter an integer\\n\"; int a{readNumber()}; //a call to the function that takes an input from user and stores it in var x and then stores that value in int a std::cout << \"Enter another integer\\n\"; int b{readNumber()}; //a call to the function that takes an input from user and stores it in var x and then stores that value in int b writeAnswer(a, b); //a call to the function that stores two int vars and produce their sum which it produces here the sum of the vars a and b return 0; } ``` ```C++ #include // These are the forward declarations for the functions in io.cpp int readNumber(); void writeAnswer(int x, int y); int main() { std::cout << \"Enter an integer\\n\"; int a{readNumber()}; //a call to the function in io.cpp that takes an input from user and stores it in var x and then stores that value in int a std::cout << \"Enter another integer\\n\"; int b{readNumber()}; //a call to the function in io.cpp that takes an input from user and stores it in var x and then stores that value in int b writeAnswer(a, b); //a call to the function in io.cpp that stores two int vars and produce their sum which it produces here the sum of the vars a and b return 0; } ``` -------------------------------- ### Iterating Through C-style Arrays Using Pointer Arithmetic Source: https://www.learncpp.com/cpp-tutorial/pointer-arithmetic-and-subscripting This C++ example illustrates iterating through a C-style array using pointer arithmetic. It initializes a `begin` pointer to the start of the array and an `end` pointer to one-past-the-end, then traverses the array by incrementing `begin` until it equals `end`. ```cpp #include #include int main() { constexpr int arr[]{ 9, 7, 5, 3, 1 }; const int* begin{ arr }; // begin points to start element const int* end{ arr + std::size(arr) }; // end points to one-past-the-end element for (; begin != end; ++begin) // iterate from begin up to (but excluding) end { std::cout << *begin << ' '; // dereference our loop variable to get the current element } return 0; } ``` -------------------------------- ### C++ Implementation: Main Game Entry Point Source: https://www.learncpp.com/cpp-tutorial/chapter-8-summary-and-quiz The `main` function serves as the entry point for the Hi-Lo game. It initializes game parameters (minimum, maximum, tries) and orchestrates the game loop by calling `play_hilo` and `wants_to_replay` until the user decides to stop playing. ```cpp #include "hi_lo.h" #include "output.h" #include "input.h" int main() { constexpr int min {1}; constexpr int max {100}; constexpr int tries {7}; do { play_hilo(min, max, tries); } while(wants_to_replay()); print_end(); return 0; } ``` -------------------------------- ### C++ Basic Sequential Execution Example Source: https://www.learncpp.com/cpp-tutorial/control-flow-introduction This C++ code snippet demonstrates a basic straight-line program. It prompts the user for an integer, reads the input, and then prints the entered value. The execution path is strictly sequential from top to bottom. ```cpp #include int main() { std::cout << "Enter an integer: "; int x{}; std::cin >> x; std::cout << "You entered " << x << '\n'; return 0; } ```