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 variable’s 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 (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 or linker 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

Be sure to use your editor’s auto-formatting feature to keep your formatting consistent and make your code easier to read.

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.12 -- How to design your first programs

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

  • letsgetit

    Sharing my initial solution for question 1.  For optimization, could have ditched the sum variable in main and combined lines 23 and 24 similar to the author's solution..but it works. Enjoying seeing the overall progress.  Looking forward to chapter 3!  

  • Waldo Lemmer

    1. The questions' solutions have spaces before the brace pairs, e.g.:

    2. I just realized your syntax highlighter colors cin and cout differently:

    • Alex

      The spaces before the brace pairs is fine. Personally I think it's easier to read.

      I just checked the syntax highlighter reserved word list and it's all messed up. I'll have to spend some time redoing it to fix the issue. I've removed cout from the list since cout is not a reserved word. Thanks for bringing this to my attention.

  • Mal

    Using Visual Studio 2019, it took me quite a while to work out why errors were being flagged up when I was writing the io.cpp & io.h files because the code looked correct.  I then discovered by accident that if I saved the project (File> Save all) the errors disappeared.  Maybe worth flagging this up to people.

    Great tutorial btw :)

    • Alex

      When I compile using VS2019, it auto-saves all the files. There may be a setting somewhere that controls this, perhaps in Tools->Options?

  • Jerome

    Hey, just wanted to check if my solution was fine or contains any bad habits.
    Thank you alot for the great tutorial!

    io.h

    io.cpp

    main.cpp

    • iban

      when you initialize "x" on main.cpp
      on line 5, here:
      int x{ readNumber() + readNumber() };

      in a lesson it is mentioned that when two functions are introduced in an initialization, they will probably not execute in the expected order, so you should try:

      int x{ readNumber() };
      int y{ readNumber() };

      That is the only bad habit I can see.

      • Dasu Pradyumna

        I don't know whether it's a bad habit or not.
        But functions in an expression are executed left to right.
        So, in Jerome's example, the left readNumber() will be executed before the right one.

        iban, what you are talking about is in the context of 2 different arguments to a function. In the above case, both the function calls are done in a single argument only.

        • Sampo

          To quote the standard: "Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again."

          For further, see: https://en.cppreference.com/w/cpp/language/eval_order

  • Armando IG

    Hello! I would love some feedback on formatting or optimization on my answer of question 1, THANKS!
    Also, I prefer forwarding so I can see my main on top... if that is ok

    • nascardriver

      If it's auto-formatted, it's well-formatted. How you configure your auto-formatter is personal preference.

      There's nothing to be optimized here, good job!

  • Rascal

  • Brett

    When compiling all functions in main, the program compiles & executes as intended

    When splitting into multiple functions, the first function of main completes, before terminating with code 0. The other functions do not execute. What am I missing?

    • Brett

      I fixed it with the following modification, However writeNumber serves essentially no purpose, as the code is repeated in main

      • nascardriver

        Line 32: You're not calling `writeNumber()`, you're declaring it. If you want to call a function, you don't need to write down the return type.

        Line 19 causes undefined behavior because `z` is uninitialized.

  • Deva_B.D.M.

    is this good programmer code???

    • Woop

      writeAnswer function is way too specific and it's only one line of code, not worth making it separate. And think of it this way, you generally want to specify a function when you use some code repeatedly, there's almost no possibility that you're actually going to need that answer twice. And readability kinda suffers, imagine you actually had some code inbetween those blocks, other functions, some statements inside main(), it would be much harder to understand what's going on.

  • MeNinja

    #include <iostream>
    using namespace std;
    int readNumber( int x, int y )
    {
       return x + y;
    }
    void writeAnswer( int result )
    {
       cout << "Result of sum: " << result;
    }
    int main()
    {
       cout << "Enter first number: ";
       int firstnumber = 0;
       cin >> firstnumber;
       cout << "Enter second number: ";
       int secondnumber = 0;
       cin >> secondnumber;
      writeAnswer( readNumber ( firstnumber, secondnumber) );
       return 0;
    }
    my solution :/ is this okay?

  • cong chen

    It is so good for your tutorial. In the chapter 2 , i have learnt the function and header file. However, i didn't really understand whenever we use a founction or header file.like this:

    and like this:
    main.cpp

    and add.h

  • Jonathan Roberts

    Thanks for your excellent tutorial.
    In Chapter 2 Summary, Quiz Question 3,
    I understand that the forward declaration, using #include "io.h" in main.cpp is needed, however, I am having trouble understanding why it is also needed in io.cpp?
    (As shown in the Solution.)

    • nascardriver

      This is explained in lesson 2.10
      https://www.learncpp.com/cpp-tutorial/header-files/#corresponding_include

      • Jonathan Roberts

        Thank you very much for your quick response.
        I have read through the section which you referred me to, however, I still can't get my head around this completely. No doubt it will become clearer to me as I work through more complex examples.
        Much obliged.

        • Zheng Wei

          From my understanding, by including the header file inside the source file (io.h inside of io.cpp) it helps to detect return type errors in function declaration/ definition which otherwise would not have thrown an error. This is especially important when writing a library as the function is not called.
          If you refer to the comment in "https://www.learncpp.com/cpp-tutorial/header-files/#corresponding_include", the error was thrown as mew() initially had the return type of char * (the string equivalent in C++) in the function declaration inside of cat.hpp while the return type of the function definition inside of cat.cpp was std::string.

          • Jonathan Roberts

            Thank you very much for your feedback Zheng. I understand the logic of your explanation, and will, from now on, always #include a .hpp in corresponding .cpp.
            Since you pointed out about the return type mismatch, it is much clearer.
            Much obliged.

  • Thomas Judge

    //Code blocks do not appear to work following edits.

Leave a Comment

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