Search

2.x — Chapter 2 summary and quiz

Quick Summary

A function is a reusable sequence of statements designed to do a particular job. Functions you write yourself are called user-defined functions.

A function call is an expression that tells the CPU to execute a function. The function initiating the function call is the caller, and the function being called is the callee or called function. Do not forget to include parenthesis when making a function call.

The curly braces and statements in a function definition are called the function body.

The return type of a function indicates the type of value that the function will return. The return statement determines the specific return value that is returned to the caller. This process is called return by value. Functions can have a return type of void if they do not return a value to the caller. Failure to return a value from a non-void function will result in undefined behavior.

The return value from function main is called a status code, and it tells the operating system (and any other programs that called yours) whether your program executed successfully or not. By consensus a return value of 0 means success, and a positive return value means failure.

A function parameter is a variable used in a function where the value is provided by the caller of the function. An argument is the specific value passed from the caller to the function. When an argument is copied into the parameter, this is called pass by value.

C++ does not define whether function calls evaluate arguments left to right or vice-versa.

Function parameters and variables defined inside the function body are called local variables. The time in which a variable exists is called its lifetime. Variables are created and destroyed at runtime, which is when the program is running. A variables scope determines where it can be accessed. When a variable can be accessed, we say it is in scope. When it can not be accessed, we say it is out of scope. Scope is a compile-time property, meaning it is enforced at compile time.

Refactoring is the process of breaking down a larger function into many smaller, simpler functions.

Whitespace refers to characters used for formatting purposes. In C++, this includes spaces, tabs, and newlines.

A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier. To write a forward declaration for a function, we use a function prototype, which includes the function’s return type, name, and parameters, but no function body.

A definition actually implements the (for functions and types) or instantiates (for variables) an identifier. A declaration is a statement that tells the compiler about the existence of the identifier. In C++, all definitions serve as declarations. Pure declarations are declarations that are not also definitions (such as function prototypes).

Most non-trivial programs contain multiple files.

When two identifiers are introduced into the same program in a way that the compiler can’t tell them apart, the compiler or linker will produce a naming collision. A namespace guarantees that all identifiers within the namespace are unique. The std namespace is one such namespace.

The preprocessor is a process that runs on the code before it is compiled. Directives are special instructions to the preprocessor. Directives start with a # symbol and end with a newline. A macro is a rule that defines how input text is converted to a replacement output text.

Header files are files designed to propagate declarations to code files. When using the #include directive, the #include directive is replaced by the contents of the included file. When including headers, use angled brackets when including system headers (e.g. those in the C++ standard library), and use double quotes when including user-defined headers (the ones you write). When including system headers, include the versions with no .h extension if they exist.

Header guards prevent the contents of a header from being included more than once into a given code file. They do not prevent the contents of a header from being included into multiple different code files.

Quiz time

Question #1

Write a single-file program (named main.cpp) that reads two separate integers from the user, adds them together, and then outputs the answer. The program should use three functions:

  • A function named “readNumber” should be used to get (and return) a single integer from the user.
  • A function named “writeAnswer” should be used to output the answer. This function should take a single parameter and have no return value.
  • A main() function should be used to glue the above functions together.

Show Hint

Show Hint

Show Solution

Question #2

Modify the program you wrote in exercise #1 so that readNumber() and writeAnswer() live in a separate file called “io.cpp”. Use a forward declaration to access them from main().

If you’re having problems, make sure “io.cpp” is properly added to your project so it gets compiled.

Show Solution

Question #3

Modify the program you wrote in #2 so that it uses a header file (named io.h) to access the functions instead of using forward declarations directly in your code (.cpp) files. Make sure your header file uses header guards.

Show Solution


3.1 -- Syntax and semantic errors
Index
2.13 -- How to design your first programs

6 comments to 2.x — Chapter 2 summary and quiz

  • WSLaFleur

    So, here's my code for Quiz time, Question #1:

    When I spoiled the answer, I was surprised that you weren't using the initialization method you described for the variables (i.e. {}). Is this just something that wasn't updated to reflect changes to the core material?

    Also, I don't really understand what I'm doing with std::cin.ignore(2) - the program is running as intended, but unless I feed the cin.ignore function a value greater than 1, it fails to pause. If you're not too busy to explain, then do you know why this is happening?

    • Hi!

      > I was surprised that you weren't using the initialization method you described for the variables
      Alex didn't update most of the lessons yet. Chapter D and onward use copy- and direct initialization.

      * Line 8: Limit your lines to 80 characters in length for better readability on small displays.
      * Line 22: Don't compare booleans to false/true.
      * Use the auto-formatting feature of your editor.
      * Line 25: Declare one variable per line.
      * Don't use @system.
      * Line 13: Initialize to a specific value (0).

      @std::cin.ignore(count, delim) ignores all characters until delim is found or count characters have been ignored.
      By passing 1 you're ignoring at most 1 character. Since the only character left by @readNumber is a line feed (Because you press enter and @std::cin::operator>> doesn't remove the line feed), this line feed is removed and execution continues.
      If you pass 2 and the only character is a line feed, @std::cin.ignore will halt until a second character has been entered.
      Pass @std::numeric_limits<std::streamsize>::max() and '\n':

      If you don't understand a standard function, you can look them up in a documentation: https://en.cppreference.com/w/cpp/io/basic_istream/ignore
      These might be hard to understand just yet, but once you know C++, a good documentation is priceless.

      • WSLaFleur

        Thanks for the reply, I've been using cppreference to dig into any syntax I'm unclear or just curious about, but I'm unfamiliar with concepts like 'delim', which makes understanding the full context difficult sometimes.

        So I tend to squirrel down a rabbit hole of syntax links for a while and then return to writing my code after a bit. I realize we haven't hit booleans yet, I'll definitely adopt best practices for them whenever we arrive.

        Thanks again!

  • Suyash

    #include <iostream>

    using namespace std;

    int readNumber();
    int writeAnswer();

    int main()
    {
        cout<<"Welcome "<<endl;
        cout<<"Enter your number "<<endl;
        int a=readNumber();//Unused variable
        cout<<"Enter the other number "<<endl;
        int b=readNumber();//Unused variable
        cout<<"The total is "<<writeAnswer();
        return 0;
    }
    int readNumber()
    {
        int x;
        cin>>x;
        return x;
    }
    int writeAnswer()
    {
        int a,b;//uninitialized variable
        return a+b;
    }

    /*
    Hello Alex,
    I wrote this after reading all three of the quiz questions, therefore I used declarations so as to make it easy for me for the next two. It compiles, but shows four  warnings, stating 1. Unused variables, 2.Uninitialized variable for each a&b. I modified writeAnswer (And its declaration) to:
    void writeAnswer();
    void writeAnswer()
    {
        int a;//uninitialized variable
        cout<<a;
    }
    but then it shows an error saying:
    too many arguments to function 'void writeAnswer()'
    but then I initialised it in my declaration. so the other two errors are left
    no match for 'operator<<'
    and whole lot of ostream errors.

    Thank you! for the tutorials
    */

    • Hi!

      Functions cannot see variables declared inside other functions. @writeAnswer doesn't know about @a and @b in @main. You have to pass them as arguments.
      @a and @b in @main get assigned a value, but after that, they're never used.
      If @writeAnswer is declared

      the "void" means that it doesn't return a value. But in @main you're trying to print the value returned by @writeAnswer. This value doesn't exist, so you get an error.
      Please use code tags (Yellow box below the comment text field) and exact error messages.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]