1.x — Chapter 1 summary and quiz

Quick Summary

A statement is a type of instruction that causes the program to perform some action. Statements are often terminated by a semicolon.

A function is a collection of statements that execute sequentially. Every C++ program must include a special function named main. When you run your program, execution starts at the top of the main function.

Preprocessor directives tell the compiler to perform a special task. In this chapter, we use them to #include <iostream>, which allows us to access the input/output routines in the standard library.

The rules that govern how elements of the C++ language are constructed is called a syntax. A syntax error occurs when you violate the grammatical rules of the language.

Comments allow the programmer to leave notes in the code. C++ supports two types of comments. Line comments start with a // and run to the end of the line. Block comments start with a /* and go to the paired */ symbol. Don’t nest comments.

You can use comments to temporarily disable lines or sections of code. This is called commenting out your code.

Data is any sequence of symbols that can be interpreted to mean something. A single piece of data, stored somewhere in memory is called a value.

A variable is a named piece of memory that we can use to store values. A variable’s name is called an identifier. In order to create a variable, we use a statement called a definition statement. When the program is run, each defined variable is instantiated, which means it is assigned a memory address.

A data type tells the compiler how to interpret a piece of data into a meaningful value. An integer is a number that can be written without a fractional component, such as 4, 27, 0, -2, or -12.

Copy assignment (via operator=) can be used to assign an already created variable a value.

Initialization can be used to give a variable a value at the point of creation. C++ supports 3 types of initialization: copy initialization, direct initialization, and uniform initialization.

You should prefer uniform initialization over the other initialization forms, and prefer initialization over assignment.

Although you can define multiple variables in a single statement, it’s better to define and initialize each variable on its own line, in a separate statement.

std::cout and operator<< allow us to output an expression to the console as text. std::endl outputs a new line character, forcing the console cursor to move to the next line. std::cin and operator>> allow us to get a value from the keyboard.

A variable that has not been given a value is called an uninitialized variable. Trying to get the value of an uninitialized variable will result in undefined behavior, which can manifest in any number of ways.

C++ reserves a set of names called keywords. These have special meaning within the language and may not be used as variable names.

A literal constant is a fixed value inserted directly into the source code. Examples are 5 and “Hello world!”.

An operation is a mathematical calculation involving zero or more input values, called operands. The specific operation to be performed is denoted by the provided operator. The result of an operation produces an output value.

Unary operators take one operand. Binary operators take two operands, often called left and right. Ternary operators take three operands.

An expression is a combination of literals, variables, operators, and function calls that are evaluated to produce a single output value. The calculation of this output value is called evaluation. The value produced is the result of the expression.

An expression statement is an expression that has been turned into a statement by placing a semicolon at the end of the expression.

Programming is hard, and your programs will rarely come out perfect (or close to it) the first time. Get your programs working first, then refine them into something great.

Quiz time

Question #1

What is the difference between initialization and assignment?

Show Solution

Question #2

When does undefined behavior occur? What are the consequences of undefined behavior?

Show Solution

Question #3

Write a program that asks the user to enter a number, and then enter a second number. The program should tell the user what the result of adding and subtracting the two numbers are.

The output of the program should match the following (assuming inputs of 6 and 4):

Enter an integer: 6
Enter another integer: 4
6 + 4 is 10.
6 - 4 is 2.

Show Solution

2.1 -- Introduction to functions
1.10 -- Developing your first program

613 comments to 1.x — Chapter 1 summary and quiz

  • Marek

    first you stress in chapter 1.6 that variables should be initialized but in the solution to question 3 you leave them uninitialized. Is this because the example is so trivial there is no place for error? Even so you should probably stick to what you teach...

    • Alex

      No, it's because I simply overlooked updating them when I rewrote the lesson. They've been fixed now. Thanks for pointing out the inconsistency.

  • Arthur

    in the answer for question 3 lines 13 and 14 end with [code]<< ".\n";[code] where I had written/expected [code]<< '\n';[code] and am unsure if that is typo or either will do the same thing? I am working in notepad for now deciding if I have any aptitude before committing to software installs so thought I would ask. thanks for the tutorial it is well written with good explanations.

  • paparob76


    I am trying to compile the answer to question 3 and my code doesn't compile. It give two error messages. Here's the code and error messages:

    Here are the error messages:

    15  error: expected ';' before string constant
    16  error: expected ';' before string constant

    lines 15 and 16 are the std::cout for the output calculations. There are ';' at all the right places.

    I'm using Code::Blocks 17.12, and I used all the setup parameters in your tutorial.
    Please help.

  • Louis Cloete

    In Quiz Question #3, maybe this would be better?

  • J Voki

    Hello guys,

    now I am a bit confused with this quiz. Here we just state "writeAnswer(x+y)" and "writeAnswer(int x)", why we dont have to make another function "add(int x, int y)" with "return x+y" here? What confuses me here, that if C++ can just go for "writeAnswer(int x)" and "writeAnswer(x+y)" what would be the point using functions like "add" etc. if we can just skip them like that?

    Thank you


  • n1fty



  • Oscar R.

    Hey guys i would like to see if this code is good / needs any improvements.




    • Hi Oscar!

      * io.cpp:29: Use double literals when calculating with doubles (2.0 instead of 2)
      * io.cpp:29, 34: Magic numbers. Declare a constant (Initialized by a literal or @std::acos(-1.0) )
      * Variables names should be descriptive. Use single-letter names for iterators only.

      @main.cpp is too densely packed, making it harder to read than this for example

      • Oscar

        Thanks for the response!

        >Variables names should be descriptive. Use single-letter names for iterators only.

        How do you recommend I do this?

        • Following your current naming convention,

  • Boteomap2

    Hello Alex, I have a question. I created IO.h with righ click in Header Files folder -> new, then in main.cpp i write #include"io.h", then i build it, error say can't not find my header file. May i add header file not correct?

  • Kkolonias

    Hi i just wanted to ask something.What could i do if i wanted to have two variables in the read function,and i wanted to give for example r variable (in the main function) the value of x and in i variable the value of y.Here is an example:
    int re(){
        int x;
        int y;
        return x;

    int main()
        int x;
        x =re();
    int y=re();

        cout <<x <<endl;//i know i have return x but if i wanted y = y(from re)
        return 0;
    do i have to change something in return(in re function);
    ....sorry for my bad english

    • Kkolonias

      actually,i just found a way to do that(return two values and select whatever i want in main function)but its not so convinient.The way is:working with if.What do you think?
      here is an example:#include <iostream>

      #include <cstdlib>
      bool r;
      using namespace std;
      int re(){
      int x;
      x =2;
      int y=5;

      if(r){return x;}
      else{return y;}

      int main()
          int x;
          int y;
          cout << x <<endl;

          cout <<y<<endl;
          return 0;

    • Benur21

      Your re function is always returning 3 (in your first code), because you set it to return x, which is always 3 when the function is run.
      You can't really do

      and expect x to have value of 3, and y value of 2, as you are using the same re() for both. But you can do something that makes it decide whether to return x or y, as you did in the second code. You did create a global boolean variable that you use to decide if you want it to return x or y. You could also use it as a parameter in the function re(), so you would use, for example, re(true) to return x, and re(false) to return y. Instead of a boolean you could also use a number re(0) and re(1), or a char re("x") and re("y").
      You could also make it so the function would return x the first time it is called, and y the second time. For this you can use the boolean you created, but instead of changing it in main(), you would switch it inside re() (in the end), using

      . This way:

  • Timmy210

    Hi, I'm getting a weird error when I try question 3. My code works fine, but when I move the forward declarations into the header file, I get this error.

    Undefined symbols for architecture x86_64:
      "readNumber()", referenced from:
          _main in main-b53dac.o
      "writeAnswer(int)", referenced from:
          _main in main-b53dac.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

    However, my code works fine when I have the forward declarations in main.cpp. Here are all 3 of my classes.


    #include "io.hpp"
    #include <iostream>

    using namespace std;
    int main()
        int y = readNumber();
        return 0;


    #ifndef IO_H
    #define IO_H

    int readNumber();
    void writeAnswer(int y);

    #endif IO_H


    #include <iostream>
    using namespace std;
    int readNumber()
        cout << "Enter a number.";
        int x;
        cin >> x;
        return x;
    void writeAnswer(int y)
        int x = readNumber();
        cout << "x + y = " << y + x << endl;


    Pls help!

    • Hi Timmy!

      Your compiler isn't automatically compiling all source files. It seems as though it only compiles @main.cpp but not @io.cpp.
      Which compiler/IDE are you using? You're best off googling for how to add source files in your IDE.

      • Timmy210

        I am using Visual Studio Code.

        • nascardriver

          With which compiler?

            • nascardriver

              g++ ./io.cpp ./main.cpp

              • Timmy210

                I ran that in terminal and got this error when I tried to run the program again:

                Undefined symbols for architecture x86_64:
                  "_main", referenced from:
                     implicit entry/start for main executable
                ld: symbol(s) not found for architecture x86_64
                clang: error: linker command failed with exit code 1 (use -v to see invocation)

                • That happens when you write

                  Because then there is not @main function. Make sure you're compiling both files at the same time as I showed in my previous comment.

                  • Timmy210

                    I did, I typed g++ ./io.cpp ./main.cpp in my terminal. is that what I'm supposed to do?

                    • It is and works fine for me. I don't know what else could be causing this problem, because g++ seems to find both @io.cpp and @main.cpp but it doesn't appear to compile @main.cpp. It should only be complaining about

                      supposed to be

                      You can try fixing this, maybe there's a bug in your version of g++. If this doesn't work try using clang++ instead of g++. If it still doesn't work then, I can't help you any further. Let me know how you solved the issue once you do so.

                  • Timmy210

                    When I do:

                    g++ -c io.cpp
                    g++ -c main.cpp
                    g++ io.o main.o -o test1

                    in terminal, I can then run my test1.exe from my finder and it works. The program also runs when I use Xcode.  However, if I try to run the program from VSCode it does not work. Seems like VScode can't properly link the main.cpp and io.cpp, even though I did so from terminal.

  • Matt

    What is your opinion on my code? I wanted to focus mine around flexibility, so the program is able to add more than 2 numbers if it wants to, although in this example to add only 2 numbers, 2 is passed into the readNumber function as an unsigned integer.

    I have an io.cpp and io.h file, the .cpp file containing definitions for each function, and the header file containing the declarations.

    I've utilised both the #pragma once preprocessor and header guards in the .h file. To defend against header duplications even further though (correct me if I'm wrong on this), I've delegated #include<iostream> to the io.cpp file rather than the io.h file. This is because the associated header file doesn't need to know about the functions iostream provides (since it's only ever providing declarations for functions and not any implementions). So I'm assuming, when io.h is included within main.cpp, there would be absolutely no conflicts at all (detectable by #pragma once or header guards) if iostream were to be included in main.cpp as well.




    • Hi Matt!

      Use either #pragma once or header guards, not both. There are only downsides from using both. Your header guard is missing #define IO

      > I've delegated #include<iostream> to the io.cpp
      Good choice. Have as few includes in headers as possible.

      * Line 5, 6, 8: Use uniform initialization
      * Line 8: Use ++prefix unless you need postfix++

  • B


    Below is my code for the 1st question. Please let me know if this is the good method of coding?

    #include "stdafx.h"
    #include <iostream>

    int readNumber()
        int num1, num2;
        std::cout << "Enter num1:" << std::endl;
        std::cin >> num1;
        std::cout << "Enter num2:" << std::endl;
        std::cin >> num2;
        return num1 + num2;

    void writeAnswer()
        std::cout << "The final answer is:" << readNumber() << std::endl;

    int main()
        return 0;

    • Hi B!

      Please use code tags when posting code (Yellow message below the comment box).

      * Initialize your variables
      * Don't mix input and output. Store the result of @readNumber in a temporary variable before printing the final answer.

  • Alfred Aprianto

    Hey there! Thanks A LOT for this tutorial.
    I have a question tho, at question 3, my code keeps saying "error: 'readnum' was not declared in this scope"
    The thing is, it just won't work if I put the header file into the project using the IDE (Code::Blocks), but it works perfectly fine if i use #include "readnum.h". Any insights on why?

  • Brook M. Gilleland

    Thank you for maintaining this site and finding the time to help people learn C++.

    The only thing with this quiz that troubles me: I suppose we're not worried about establishing the numeric value for y or checking the console for output...?

    Not sure why I think this should be done anyways. Seems to me like I should be producing something any time I write code.

    Most sincerely, Brook

  • My solution is only slightly different to the one you supplied but build failed unless a return value was supplied in function writeAnswer().  This is using VS 2017 Community.

    • nascardriver

      Hi Nigel!

      You declared @writeAnswer to return an int. Give lesson 1.4 another read.
      If you declare a function with a return type that is non-void the function has to return a value.

      * Lesson 1.4 - A first look at functions and return values

  • Jhayar

    Here's how I solve the first part. is this less efficient than the way you showed it?

    • nascardriver

      Hi Jhayar!

      Your program isn't less efficient, but you're using global variables, which are bad, and"readNumber" doen't sound like a name for a function that perform arithmetic. "writeAnswer" also doesn't sound like a name for a function that _reads_ user input.
      Avoid reading input while writing output (Line 23).

      • Jhayar

        Thanks for your reply. I failed this quiz because I can't do the first one properly and I failed to do the other two.

        Do you think I should reread the past lessons or just move forward. thank you!

        • nascardriver

          You solved the first one, just not in a nice way. If you understand Alex' solution there's no problem.
          You should be able to solve task 2 and 3, because they are mandatory for future lessons. Re-read lesson 1.8 and 1.9, those should get you going.

  • ray

    man i literally had trouble for the first part, i wanted to cry. Ive been watching "thenewboston" videos which show it in a less technical way. so your proper way which is obviously better makes me feel like i havent learned anything ;(

  • Louis Cloete

    Is it good style to do this for main() for question 1:

    or should I use variables and assign a number to each, then add the two variables as in the answer?


  • amin

    hi, first i would like to thank you for this awesome place and for all the guidance and second
    if i have multiple user input or information that can be generally grouped together is it a bad practice to have them all in one cpp file? or each function or class needs one.

    • nascardriver

      Hi amin!

      Can you give an example for the data you're dealing with? It's hard to answer this question in a general way.

      • amin

        say for example i am making a calculator and i get the user input that is needed one is a number one is an operator should i put them in one file

        • nascardriver

          You store them in the function that asks the user to input them an then pass the numbers and operator around as function arguments.
          If you scroll through the replies on this page you can take a look at how other people dealt with this task.
          If values are related they should usually be stored together.

  • Rajsekar

    when i try to compile after creating io.cpp file it says "cout was not declared in the scope", same with after adding header file me...

  • Hervé

    Seeing as how people are all posting their calculators, I'll post mine aswell for some feedback







    I do realise I could have split more of the code from 'main.cpp' into the other files, but now that it's up and working, I dont really want to spend the time to do it. Any advice or criticism is welcome as, shown by my comment regarding the '&' sign and possibly plenty of other terminology errors, I am new to C++ any advice is helpful.

    EDIT: I just realised this was far longer than I had expected, feel free to skip a lot of the top part in 'main.cpp' as it mainly is the same thing repeated four times with minor differences each time.

    • nascardriver

      Hi Hervé!

      * Sort your includes.
      * Prefer the <c*> headers over <*.h> (<cmath> over <math.h>, <climits> over <limits.h> and so on).
      * I don't think you're using ncurses.
      * Use the namespaced versions of standard functions (std::sqrt)

      * Initialize your variables with uniform initialization.
      * Line 39-41 are equivalent to Line 46-48. Don't repeat yourself.
      * Initialize chars to 0, not '0'
      * Line 71: Avoid magic numbers. Use std::numeric_limits<double>::digits10.
      * Line 77, 81, 85 and 89 are repetitions. Don't repeat yourself. If you don't have a break in a case the code below will be executed. So you can remove the contents of all cases except case '/'.
      * You already said it, @add, @sub, @div and @mult are almost identical. Don't repeat yourself.
      * Line 412: choices != choice. If you didn't notice this you should use different names.

      Every math file:
      You don't need any of those includes. All they do is increase compilation time. You're not even using the functions in there. Remove those files.

      @choices only gets called after you've already switched the operation, but you're switching it again here.

      • Hervé

        Thanks for the feedback! I have since followed your advice and significantly cut the length of the program by deleting all four math files and combining the math functions into one. I feel kinda embarrassed to ask since you have clearly done quite a lot to help me, but I don't quite understand what you mean by 'choices != choice. If you didn't notice this you should use different names'. I realise you were pointing at the 'while(&choices)' form the do-while loop, but did you mean that the code was replacing the '&choices' by 'choice'? Sorry if my question is stupid, but I don't really have much experience with do-while loops and don't understand what you meant.

        P.S. Just being curious here but what benefits does using the namespace version of functions over the standard function give? Or is it just for good habits?

        • nascardriver

          Always ask if you don't understand something or you'll get into bad habits.

          You have a variable named "choice" and a function named "choices". I though you were trying to do some checks with the variable and accidentally added an 's' to the end.
          To be honest, I don't understand what you were trying to achieve here. I don't see a way to stop that loop so you might as well use

          > what benefits does using the namespace version of functions over the standard function give?
          No benefits. The non-namespaced versions are leftovers from earlier versions of C++ or C. Most implementations of the <c*> headers declare the functions in the global namespace, but using the namespaced variants is the proper way to access them.

          • Hervé

            Thanks again. I did mean to have 'choice' as a variable and 'choices' as a function. I was just using the do-while loop for an infinite loop although I didn't really know how to do so, I guess you just told me the answer. I also added in 'std::numeric_limits<double>::digits10' instead of 'std::cout.precision(10)' but it didn't increase the maximum accuracy of a number and ended up showing numbers with higher than 7 digits in scientific notation, did I use it wrong or something, I realise this is something I will probably learn later on, but how exactly would it avoid showing imaginary numbers and how am I supposed to implement it into the code?

            I did it like this, which is probably why I didn't get it to work?

            Many thanks again for all the help!

            • nascardriver

              is just a number, you still need to call @std::cout.precision or use @std::setprecistion.

              The advantage of using this value rather than 10 is
              a) Everyone knows what this value will do (Or look it up)
              b) This value can vary on different systems. If you use 10 and some system has a higher precision than 10 you'll be missing some digits.

  • Beesta

    So, I'm having a fun lil issue. I'm using MVS and it refuses to compile even if I use the code thats in the answers (given that I added the #include "stdafx.h")
    It's saying that cin and cout arent members of std. error code is c2039 and c2065.

    • Alex

      Assuming you haven't made an error somewhere (e.g. including iostream.h instead of just iostream), it's possible your compiler is just significantly out of date.

      • Beesta

        I'll go ahead and post my code, but its basically the same as the solutions. Also, my version of Visual Studio should be one of the newest, version 15.6.4.




        • nascardriver

          has to be the first line in @io.cpp.
          I don't know if this is the cause to your problem, I can't test it.

          • Beesta

            I thought so too, changed that but it didnt help much

            • SteveZ

              I have the same exact problem in my VS 2017.  I can't get the solution to run.  Every file is added and accounted for.  I simply get that it can't even open source file "stdafx.h" and that readNumber and writeAnswer are not identified.

  • Cumhur

    Really cool to write some codes and see they work!
    Thanks for your effort, i want to ask  at end the lessons  if i can be able to code complex 2D platform games. Thanks again!

  • Qbert


    My programs accomplish the goals of the quiz when the user inputs "expected" values. I wanted to see what happens when I try other inputs.

    Can you explain what C++ is executing when I input a decimal for the first value? What appears to happen is it does not ask for a second value, puts in an unexpected number, omits the addition, and then ends the program.

    When I put a decimal value for the second value though, it ignores everything after the decimal but runs as expected otherwise.

    I include my code below in case it is just something with the way I have written it.

    • nascardriver

      Hi Qbert!

      Anything you write into your console will be stored in a buffer. std::cin looks at that buffer and tries to extract an int from it. It doesn't care if there is anything after the int. The int will be removed from the input buffer.
      Let's look at what happens in a smaller sample program:

      Same happens with for example 123hello as input.

      Lesson 5.10 - std::cin, extraction, and dealing with invalid text input

  • Dear Teacher, please let me say you what I do not understand. I have written four files: main.cpp, io.cpp, io.h, and qio.h. In IDE online
    program works fine. But two header files are identical save their names.





  • Zane

    Las calculadoras? Si!

    Calculator Main.cpp


    • nascardriver

      Hi Zane!

      Good job solving the quiz!



  • seb

    If we're posting calculators, I guess I'll post mine.







    • nascardriver

      Hi seb!

      Since you used content that hasn't been covered yet I'll do the same.

      Line 6: Uniform initialization is preferred. (Same goes for all other initializations) (Lesson 2.1)
      Line 8: @std::cin.clear clears the error flag that gets set when an error occurs. There's no point in calling it here.
      Line 9: You're extracting input via @std::cin::operator>>. You don't need @std::cin.ignore here.
      Line 12,16: You don't need an empty string to output a new line

      Line 19: Unnecessary
      Splitting user input, calculation and printing into separate functions would've been nice.

      Line 5: Initialize your variables. (This goes for all other variables too)

      Never use goto.
      Line 16: You don't need std::getline, std::cin >> or std::cin.get are enough.
      Line 19: std::strings are converted to const char * by using std::string::c_str(). What you did might not work with all implementations of std::string.
      Line 20, 23, 26, 29: strcmp isn't used for std::strings. std::string has an == operator

      The do-while-loop isn't doing anything, because you messed everything up by using goto. If you removed the goto it should work without further changes.

      Unnecessary use of temporary. You could've returned the results of the calculations directly.

      All in all, there are sevaral issues, but that's nothing to worry about. We're at the start of the lessons and you'll learn how to do it probably.

      • seb


        Line 6: I was only aware of copy initialization when I made this. I only know what I've learned from this website, and google(which turns up old questions on stackoverflow) when I want to do something that hasn't been covered yet(I just finished chapter 2.1).

        Line 8: ok.

        Line 9: I do need this, or the next function thinks I'm still pressing return and tries to skip a part of my program.

        Line 12, 16: I know what happened here. I tried using std::endl by itself at some point, and I also probably tried using std::cout << << std::endl (unaware of the proper usage of << at the time). I found something that worked and kept using it.

        line 19: I like to test my compiled applications outside of the ide.

        "Splitting user input, calculation and printing into separate functions would've been nice." Easy now, this is just a test program to help me get my bearings (which hours to make). I have zero previous experience with c++, almost zero with programming in general, and am doing this as a hobby (using whatever resources I can find online). I'm just happy it works.


        line 5: int a; is initialized via std::cin > a; on the next line. I don't see the problem.


        what's wrong with goto?
        (scratch that, I looked it up)
        if goto is depreciated, shouldn't it be removed from the c++ standard library?

        line 16: I print a "'user input' is an invalid operator" statement using the input from getline;
        I used cin.get at first, but if any spaces are entered into the console, I get multiple such statements, since each character or set of characters after a space is treated as a new entry.

        line 19: "What you did might not work with all implementations of std::string."
        I'm not exactly sure what you mean by "all implementations of std::string", but I think I catch your drift.

        Line 20-29: Oh, so I can use the string directly. (I had it converted for something else that I removed. I think I was trying to return the string to main as a char array. I just learned about pointers and references while trying to do something else today; but they seem kind of unreliable, I must be using them wrong).

        "The do-while-loop isn't doing anything"
        I had to search online to figure out how to use a loop at all. I'd been learning c++ for maybe 3 days (so like 5 or 6 now?).

        You're right, the loop works fine without goto, but I get the warning "label LOOP defined but not used", for some reason (which may be why I thought I needed goto in the first place).

        Unnecessary use of temporary."
        stylistic preference. (you're referring to int d; right?)

        • nascardriver

          > int a; is initialized via std::cin > a;
          That's not an initialization, that's an assignment. You shouldn't rely on functions to be able to handle uninitialized variables.

          > if goto is depreciated, shouldn't it be removed from the c++ standard library
          The problem with removing deprecated features is that there is still source code out there that's using these features and you wouldn't be able to compile them if it was just removed. It'd be nice if these features were marked as deprecated by IDEs, but unfortunately that's not a thing.

          > but I get the warning "label LOOP defined but not used"
          Labels are only used in combination with goto, they don't serve a purpose on their own.

          > you're referring to int d; right?
          Yep. I do it like you do when I'm debugging and I want to see the value before it's returned. Your compiler will remove the temporary to increase performance so there's no difference in the end, but I like imagining that my compiler doesn't optimize stuff.

          For 3 days of learning you've done a good job, keep it up!

          • seb

            "That's not an initialization, that's an assignment. You shouldn't rely on functions to be able to handle uninitialized variables."

            Assigned, my bad; I'm still new to the terminology.
            (I know the difference but didn't think to express that awareness).

            So if I want an empty variable, I  should just initialize it with a zero?
            int a{0};

            "Labels are only used in combination with goto, they don't serve a purpose on their own."

            Oh, ok. so just do{}while; and not{}while;

            "Your compiler will remove the temporary to increase performance so there's no difference in the end, but I like imagining that my compiler doesn't optimize stuff."

            Are some compilers better than others at optimization, or just in general?
            I'm using mingw-w64 (w/ code::blocks).

            • nascardriver

              > So if I want an empty variable, I  should just initialize it with a zero?
              If it's a number, yes. For other data types you use their default value (0, 0.0, 0.0f, "", nullptr, etc.)

              > Oh, ok. so just do{}while; and not{}while;
              Yes, do-while-loops are covered in lesson 5.6

              > Are some compilers better than others at optimization
              Probably, but I don't know which ones are better than others.

  • mitch

    what does this have to do with bernie sanders?

  • Yus K





    I tried the calculator example using a bit of my own addings also to practice my skills.

    Looking back at this code my ideas of what can be added are
    1) Header guards (didn't understand this correctly so i have to re read the chapter)
    2) Use comments to leave notes explaining useful info

    If anyone has any advise on my code, or anything to add please post as im new and eager to learn from people who have more knowledge than myself

    • nascardriver

      Hi Yus!

      Bad file name, the file extension says it's it header, having 'Header' in the name is redundant.

      Bad file name, stick to letters, underscores (and numbers).
      Also, since this is the source file defining the functions declared in @CalculatorHeader it should have the same name.
      Line 6, 13: Initialize your variables.

      @y: Bad variable name, operation or similar is better.

      You'll learn about further improvements to your code in upcoming lessons. So far you've done a good job.

  • Jimi

    The calculator i made is a little unnecessarily complicated as while making it i wanted to try out things like the if and goto commands, as well as make sure i’ve got a handle on all the things discussed in older lessons.





    • Jimi

      Oh, and all the std::cout << std::endl; statements are there just to add newlines into the program. Really they're pretty unnecessary as they make the code more difficult to read while making the program a little prettier. I'm sure there's a better way to add newlines but this is the only method i know.

    • nascardriver

      Hi Jimi!

      > I’m sure there’s a better way to add newlines but this is the only method i know.
      There's '\n'.
      std::cout << "Hello\nWorld" << std::endl;


      General stuff
      Don't ever use goto! All modern languages offer various other, cleaner, reader friendlier ways of achieving the same results.
      Try to limit each line to a maximum of 80 characters. Longer lines might not display correctly on small screens.

      Line 12: Bad variable name

      Line 4: Unnecessary forward declaration, this will add extra work if you decide to change the function signature
      Line 8: Initialize your variables, this goes for all other variable declarations, I won't list all of them
      @askInput and @recordInput could be merged into one function to prevent the creation of 1 variable and 1 function call

      Line 4: Bad function name or behavior. @doMath should do math and not print anything or have a different name.
      Line 6+: Use 'else if'

      PS: Edit your posts instead of deleting and re-posting. Syntax highlighting will work after refreshing the page.

      • Jimi

        Thank you for the feedback!
        I agree that some variables and functions have dumb names, I initially mixed up some variables and had issues because of that.

        A few notes though.

        In doMath last.cpp, how would I use else if? Maybe I don't fully understand the statement, but I don't think I need to do anything if, for example, x was not 1.

        The reason recordInput is it's own function is because it's being used by main, askInput and askOperand. I can reuse the function that way.

        • nascardriver

          > In doMath last.cpp, how would I use else if?

Leave a Comment

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