**Unary arithmetic operators**

There are two unary arithmetic operators, plus (+), and minus (-). If you remember, unary operators are operators that only take one operand.

Operator | Symbol | Form | Operation |
---|---|---|---|

Unary plus | + | +x | Value of x |

Unary minus | - | -x | Negation of x |

The unary plus operator returns the value of the operand. In other words, +5 = 5, and +x = x. Generally you won’t need to use this operator since it’s redundant. It was added largely to provide symmetry with the unary minus operator.

The unary minus operator returns the operand multiplied by -1. In other words, if x = 5, -x = -5.

For best effect, both of these operators should be placed immediately preceding the operand (eg. `-x`

, not `- x`

).

Do not confuse the unary minus operator with the binary subtraction operator, which uses the same symbol. For example, in the expression `x = 5 - -3;`

, the first minus is the subtraction operator, and the second is the unary minus operator.

**Binary arithmetic operators**

There are 5 binary arithmetic operators. Binary operators are operators that take a left and right operand.

Operator | Symbol | Form | Operation |
---|---|---|---|

Addition | + | x + y | x plus y |

Subtraction | - | x - y | x minus y |

Multiplication | * | x * y | x multiplied by y |

Division | / | x / y | x divided by y |

Modulus (Remainder) | % | x % y | The remainder of x divided by y |

The addition, subtraction, and multiplication operators work just like they do in real life, with no caveats.

Division and modulus (remainder) need some additional explanation.

**Integer and floating point division**

It is easiest to think of the division operator as having two different “modes”. If both of the operands are integers, the division operator performs integer division. Integer division drops any fractions and returns an integer value. For example, 7 / 4 = 1 because the fraction is dropped. Note that integer division does not round.

If either or both of the operands are floating point values, the division operator performs floating point division. Floating point division returns a floating point value, and the fraction is kept. For example, 7.0 / 3 = 2.333, 7 / 3.0 = 2.333, and 7.0 / 3.0 = 2.333.

Note that trying to divide by 0 (or 0.0) will generally cause your program to crash, as the results are undefined!

**Using static_cast<> to do floating point division with integers**

In section 2.7 -- Chars, we showed how we could use the static_cast<> operator to cast a char to an integer so it would print correctly.

We can similarly use static_cast<> to convert an integer to a floating point number so that we can do floating point division instead of integer division. Consider the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> int main() { int x = 7; int y = 4; std::cout << "int / int = " << x / y << "\n"; std::cout << "double / int = " << static_cast<double>(x) / y << "\n"; std::cout << "int / double = " << x / static_cast<double>(y) << "\n"; std::cout << "double / double = " << static_cast<double>(x) / static_cast<double>(y) << "\n"; return 0; } |

This produces the result:

int / int = 1 double / int = 1.75 int / double = 1.75 double / double = 1.75

**Modulus (remainder)**

The modulus operator is also informally known as the remainder operator. The modulus operator only works on integer operands, and it returns the remainder after doing integer division. For example, 7 / 4 = 1 remainder 3, thus 7 % 4 = 3. As another example, 25 / 7 = 3 remainder 4, thus 25 % 7 = 4.

Modulus is very useful for testing whether a number is evenly divisible by another number: if x % y == 0, then we know that y divides evenly into x.

For example, say we wanted to write a program that printed every number from 1 to 100 with 20 numbers per line. We could use the modulus operator to determine where to do the line breaks. Even though you haven’t seen a while statement yet, the following program should be pretty comprehensible:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> int main() { // count holds the current number to print int count = 1; // start at 1 // Loop continually until we pass number 100 while (count <= 100) { std::cout << count << " "; // print the current number // if count is evenly divisible by 20, print a new line if (count % 20 == 0) std::cout << "\n"; count = count + 1; // go to next number } // end of while return 0; } // end of main() |

This results in:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

We’ll discuss while statements in a future lesson.

**A warning about integer division and modulus with negative numbers prior to C++11**

Prior to C++11, if either of the operands of integer division are negative, the compiler is free to round up or down! For example, -5 / 2 can evaluate to either -3 or -2, depending on which way the compiler rounds. However, most modern compilers truncate towards 0 (so -5 / 2 would equal -2). The C++11 specification changed this to explicitly define that integer division should always truncate towards 0 (or put more simply, the fractional component is dropped).

Also prior to C++11, if either operand of the modulus operator is negative, the results of the modulus can be either negative or positive! For example, -5 % 2 can evaluate to either 1 or -1. The C++11 specification tightens this up so that `a % b`

always resolves to the sign of `a`

.

**Arithmetic assignment operators**

Operator | Symbol | Form | Operation |
---|---|---|---|

Assignment | = | x = y | Assign value y to x |

Addition assignment | += | x += y | Add y to x |

Subtraction assignment | -= | x -= y | Subtract y from x |

Multiplication assignment | *= | x *= y | Multiply x by y |

Division assignment | /= | x /= y | Divide x by y |

Modulus assignment | %= | x %= y | Put the remainder of x / y in x |

Up to this point, when you’ve needed to add 5 to a variable, you’ve likely done the following:

1 |
x = x + 5; |

This works, but it’s a little clunky, and takes two operators to execute.

Because writing statements such as x = x + 5 is so common, C++ provides 5 arithmetic assignment operators for convenience. Instead of writing x = x + 5, you can write x += 5. Instead of x = x * y, you can write x *= y.

**Where’s the exponent operator?**

You’ll note that the ^ operator (commonly used to denote exponentiation in standard mathematical nomenclature) is a Bitwise XOR operation in C++. C++ does not include an exponent operator. To do exponents in C++, #include the <cmath> header, and use the pow() function:

1 2 3 |
#include <cmath> double x = std::pow(3.0, 4.0); // 3 to the 4th power |

Note that the parameters (and return value) of pow in the above example are of type double. std::pow() assumes the base is a floating point number. Note that due to rounding errors in floating point numbers, the results of pow() may not be precise (slightly smaller or larger than what you’d expect).

If you want to do integer base, you’re best off just using your own function to do so, like this one (that uses the non-intuitive “exponentiation by squaring” algorithm for efficiency):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// note: exp must be non-negative int pow(int base, int exp) { int result = 1; while (exp) { if (exp & 1) result *= base; exp >>= 1; base *= base; } return result; } |

Don’t worry if you don’t understand all of the parts of this function yet. Just beware of overflowing your integer result, which can happen very quickly if either argument is large.

**Quiz**

1) What does the following expression evaluate to? `6 + 5 * 4 % 3`

2) Write a program that asks the user to input an integer, and tells the user whether the number is even or odd. Write a function called isEven() that returns true if an integer passed to it is even. Use the modulus operator to test whether the integer parameter is even.

Hint: You’ll need to use if statements and the comparison operator (==) for this program. See lesson D.2.6 -- Boolean values and an introduction to if statements if you need a refresher on how to do this.

**Answers**

O.3.3 -- Increment/decrement operators, and side effects |

Index |

O.3.1 -- Operator precedence and associativity |

Alright, I wrote a program just for fun, to keep writing code and keep teaching the brain how to write c++ that does some mixed division with Integer and Float inputs and outputs either Integer or Float results.

User can choose whether to use static_cast or not to convert integer inputs to float.

I did it because while reading this page, I felt the need to try several division combinations mixing ints with floats, so here it goes.

The program performs the following division combos:

• Int = Int / Int

• Int = Float / Int

• Int = Float / Float

• Float = Int / Int

• Float = Float / Int

• Float = Float / Float

Note that choosing to convert Ints to Floats makes a difference when calculating Float = Int / Int. You'll know why if you read this class paying attention to what you were reading.

For anyone lurking through the comments that wants to test some division combinations, here is the program:

I'm loving programming. Why didn't I start earlier??

OK, let's jump to the quiz now. =D

my quiz#2

Hi Dimitri!

* Line 28, 29: Initialize your variables with uniform initialization. You used copy initialization.

* Line 7: Initialize your variables with uniform initialization.

* Line 14: You don't need to modify @x

Thanks nascardriver! Got it! Except * Line 7: Initialize your variables with uniform initialization

Why we need initialization there?

Assuming you're using C++11 or later, it doesn't make a difference here.

Initializing all variables will prevent you from forgetting an initialization where it's necessary.

Oh, OK! Better to assign 1 by default or it doesn't matter?

Whatever is the 0 value for your type.

int 0

float 0.0f

double 0.0

etc

Many thanks!

Hi Alex,

I have a question.

Shouldn't this got to the new line every 2 lines? 2 is evenly divisible by 20 and returns the remainder 0. Why does it still print every 20 lines?

You've got some pretty fancy math. 2/20 = 0,1

*facepalm* I just realized. its late at night and im not thinking straight... sorry xd

2/20 = 0,1

0,1 * 20 = 2

is this / symbol means Division assignment ? @nascardriver

/ division

* multiplication

+ addition

- subtraction

In the isEven() function i can up with:

I read the comments and did not find anyone who did it this way. Is this ok as well or is their a problem with it?

Hi Benjamin!

Logically, your function is equivalent to the other submissions.

But your function is less efficient, because your computer has to perform the extra step of adding 1 to @num.

Thank you! Wow i made two errors in my post. I meant "came* up with" and "or is there*". It was late at night, lol. Again thank you!

While your function mostly works, it will overflow if you pass in the largest integer.

I had the same though, but I came to the conclusion that the overflow doesn't cause any problems, so I omitted it in my reply.

Assuming 32bit integers, 2147483647 (odd) will overflow to -2147483648 (even), same for all integer widths.

The only thing I can think of is that handling the overflow could take up a neglectable amount of CPU-time.

// ConsoleApplication4.cpp : This file contains the 'main' function. Program execution begins and ends there.

//

#include "pch.h"

#include <iostream>

using namespace std;

int getNumber()

{

int x;

cout << "Please enter any number to see if it is odd or even:";

cin >> x;

return x;

}

bool calculate(int x)

{

if (x % 2 == 0)

return true;

else

return false;

}

int main()

{

int x = getNumber();

bool y = calculate(x);

if (y == true)

cout << "its even number.";

else

cout << "Its odd number.";

return 0;

}

My program works fine but i am using different approach.

Can someone please clarify if my approach is fine?

Hi Qais!

* Initialize your variables with uniform initialization.

* In @calculate, you're returning the same value as the == comparison, so you might as well return it directly.

* Don't compare booleans to false/true, they're booleans already.

* Variable names should be descriptive.

Hello there, even my code is working I don't know where should I improve it.So i hope i get some reply.

ps: about even or not even thing in printResult(),i dont know how it works(i guess it evaluates the first parametar if true, and the one after ":" if false), im new to programing, i just saw nascardriver use it in comments some tutorials before and i kinda steal that :)

Hi!

> I don't know where should I improve it

Looks fine to me :-)

> about even or not even thing in printResult [...]

That's the conditional operator. It's covered in lesson 3.4. Your description of how it works is correct.

Thanks for the replay nascardriver.Its very rare experienced programmer taking time to comment a begginer's simple programs.Its a kinda dying breed:)

Looks good, but some suggestions about general practices(more like being nit-picky :))

>> Don't(more like 'No need to') initialize the variables if you are going to override them without using the initialized values.

>> Input argument can be renamed to make it a bit more clear, something like 'is_num_even'

Hi Alex

Firstly, huge thanks for this tutorial series. You have a great teaching style, and I really like how you take the time to talk about good programming practices and pitfalls.

Regarding the following code:

I was playing around with debug->disassembly in VS2017 and noticed that this actually compiles to more instructions in assembly than the if/else version, despite it seeming shorter/simpler in C++.

I didn't check the cycles per instruction, but either way, I thought this tutorial might be a good opportunity for you to bring up the topic of premature optimisation versus code readability (especially as I understand modern compilers can optimise better than most humans, and due to modern CPU features like speculative execution).

I'm just a novice/hobbyist programmer, so I used to be a bit OCD about trying to write efficient code (or at least code that I thought was efficient), including avoiding function calls due to their overhead, but am trying now to re-train myself to prioritise code readability. Personally I think the if/else version is just a tiny bit easier to understand intuitively at a glance.

Thanks again for your work on these tutorials!

Hi David!

Assembly has a very limited instruction set, whereas C++ is huge. You'll get a lot more instructions out of your code, no matter what you write.

Low-level optimization should be left to the compiler in most cases. The programmer should prioritize optimization of algorithms, data usage, etc., because those can't be optimized by the compiler and they have a much bigger impact than a couple of unnecessary instructions.

Yep! I got a little bit of exposure to ARM assembly a while back due to trying to mod some GBA/NDS games. It was fun and I learned a lot, but man is it good to be back in a higher level language and not have to keep track of things like the stack pointer for local variables!!

Agree with your points! I didn't really appreciate that when I started programming though, which is why I thought it might be a good topic for Alex to address in these tutorials as part of good programming practices. Before I was exposed to assembly, I used to think that less C++ code meant less instructions to execute - now I know that is not necessarily the case (for the isEven() example, both versions actually compile into the same assembly for Release build - just 3 instructions)! Now I also know that less instructions does not necessarily equal better performance (or matter nearly as much as algorithms and data usage, as you say).

Hence when it comes to choosing between if/else blocks versus code that looks shorter in C++, I now try to prioritise readability. It might be different for seasoned programmers like yourself, but I have to mentally convert that single line return statement in my head into an if/else statement when reading it anyway, so the if/else version just reads a tiny bit easier for me. The following code from Chapter 3.5 puts this in starker contrast. Also harder to debug I think? Breaking it out into if/else statements made it easier to follow in the debugger for me.

> Also harder to debug

Generally, if you use more lines, it's easier to debug. Using more lines doesn't necessarily change the compiled code.

@approximatelyEqual can be expanded into multiple lines without affecting the outcome. The one-liners might be easier written if you've been coding for a while. But once something goes wrong you'll be back to if/else and temporary variables.

You can edit your posts. The syntax highlighter will work after refreshing the page.

> You can edit your posts. The syntax highlighter will work after refreshing the page.

Ha thanks! That's exactly why I deleted/re-posted. Hope you didn't have to retype your message because of that!

Great conversational points, and the reminder not to prematurely optimize your code is timely as I'm rewriting a lesson where a mention of that would be perfect.

I agree the approximatelyEqual() function is hard to read/follow and even harder to debug -- but I opted to prefer the terse version under the assumption that most readers would just use the function, not try to dissect it. :) Maybe that's the wrong call to make in a learning tutorial series...

> I'm rewriting a lesson where a mention of that would be perfect

Awesome! Is there a way to get email alerts when one of the lessons I've already worked through gets updated (and maybe also see what changed)? Couldn't find a subscribe button anywhere.

> I opted to prefer the terse version under the assumption that most readers would just use the function

Haha I think maybe you also chose it because you knew if you used the long version, you'd have to put up with lots of clever people telling you "did you know you could do that all in one line?" :p I could follow the logic in my head, but needed the debugger to figure out what was happening to the adjusted epsilon for the close-to-zero case. (Who knew multiplying a number by something <1 made that number smaller haha - my maths is sooo rusty!)

On the topic of debugging, I remember a few years ago when I first worked through these lessons (got up to Chapter 14) that the debugger was barely mentioned again after introducing it in Chapter 1 (from a quick site search it seems this is still the case). So back then I never really used the debugger - mostly due to lack of exposure and because I was used to just inserting "debug code" (eg, tracking how variables changed by printing to console), which is a habit I developed from modding games using LUA scripting. But after trying to make sense of ARM disassembly... my God how I appreciate a good debugger now!

As you update lessons for other issues, perhaps it would be helpful to start sprinkling in more exercises using the debugger (just to get new programmers more used to it). For example, in this lesson, the int pow() "exponentiation by squaring" algorithm causes an infinite loop if a negative exponent is entered. You could mention this and encourage students to use the debugger to figure out why (apparently depends on the compiler, but VS17 uses arithmetic shift right for signed int so the loop gets stuck at -1).

(I know you encourage robust code in later chapters, but I used to be super impatient and hate thinking about edge cases or investing the time/lines required. Until I started writing code to parse documents, and kept creating documents that broke my own code or which accidentally created infinite loops. Sometimes ya just gotta learn the hard way...)

There currently isn't an email alert system for lesson updates. It's been a long-standing request that I haven't yet had time to figure out how to facilitate.

> Haha I think maybe you also chose it because you knew if you used the long version, you'd have to put up with lots of clever people telling you "did you know you could do that all in one line?" :p

I didn't think of that, but it's absolutely true. :)

Adding "debug this" quiz questions is absolutely on the agenda as I rewrite. I share your feeling that learning to use the debugger effectively is a crucial skill, and this tutorial series doesn't do a good enough job reinforcing this point.

I appreciate all the feedback! If you have any other thoughts, please feel free to share them.

Hmm, the following WordPress plugins look like they might help? I don't really know much about WordPress or web development though...

https://wordpress.org/plugins/content-update-notification/

https://www.wpbeginner.com/plugins/how-to-show-post-updatesrevisions-to-your-readers-in-wordpress/

Alternatively, there is always the super low-tech but low-cost method: simply create a page to act as a manual changelog. Then from now on, whenever you update a lesson (other than typo fixes, etc) all you need to do is remember to add a one line summary to the changelog page with the date and lesson number.

> this tutorial series doesn't do a good enough job reinforcing this point

Think you're being a little bit hard on your own work there :)

There are a lot of important skills for larger projects or professional development (eg, version control, unit testing, different workflows, automating, etc) that this tutorial series couldn't possibly cover in a meaningful way without overwhelming readers and distracting from its core lessons. (I just spent a WEEK going down a Git rabbit-hole because it's integrated in Visual Studio, and that was just to learn the basics!)

What this tutorial series does do though (ie, cover fundamental C++ programming concepts step-by-step, while teaching good practices and how to avoid common pitfalls along the way), it does really REALLY well. The first time I came across this tutorial series, I had never encountered OOP, overloading, virtual functions and templates before. But this tutorial series made it a real joy to learn!

So thank YOU for all your time and effort!

Since I wanted to write a comment about the int pow() function anyway and I wholeheartedly agree with David about the absolute brilliance (excellence? I don't know what word to use, but it should mean "wayyy better than anything else I have seen") of this website, I will add my 2c here to this thread.

First, let me say that this website has been a Godsend. I am a wannabe musician, and I use MuseScore, an open-source music notation editor written in C++ and using the Qt framework. I wanted to learn to code in C++ to contribute. I have learnt a little programming (Delphi, which is a Pascal framework, and the graphical language Scratch) in high school as an additional subject after school, but I dropped out because I wanted to spend more time with my music. Now I have to brush off my extremely small knowledge of programming and learn a new language.

I just have to say, Alex, you're an awesome teacher. You know in which order to treat subjects so that it makes logical sense, you have a gift for explaining and you know the value of lots of simple, easy-to-understand examples. And that is not all, you also provide very insightful comments into why certain programming practices are bad and why you should avoid them, even if the language allows it. Textbooks never even mention programming best practices. That is the difference it makes when the teacher is working in the industry every day. You know what works and what not. Professors don't necessarily know.

Now, to my comment about the int pow() function:

changing the parameters to

will sort out the problems with the undefined behaviour. You say yourself in the tutorial about bitwise operators that unsigned integers should always be used when doing bitwise operations. It will not violate your rule that you shouldn't mix signed and unsigned integers, since the exponent is never used in an expression with a signed variable.

Hey Louis! Glad to see another huge fan of this website.

Re using an unsigned int parameter for int pow(), just be careful about C++ implicit conversion from int to unsigned int. I know because I previously tried to do exactly what you did, and was surprised that I could pass -1 to exp without any error/warning from the compiler. Not what you want because -1 becomes a very very large unsigned int!

I haven't tried this yet but apparently you can use templates (which is introduced in Chapter 13) to prevent such implicit conversions (see https://stackoverflow.com/a/44412113). If it works, would save on having to do error handling for exp < 0.

Well, yeah, of course C++ would implicitly convert the int -1 to an unsigned int, but I figured it is better to let the loop iterate for a very large finite amount of iterations than to have an infinite loop.

Using unsigned int has the added benefit of telling the programmer that the function expects a positive number. The comment will never be seen if you put the function into a library and write a header file for it.

Maybe the best solution would be to figure out what is the largest exponent you can give the function without overflowing the int return value and test to see if your unsigned int is smaller than that. You should just use sizeof(int) to figure out if you are dealing with 16-bit or 32-bit ints.

I didn't read the stackoverflow thread yet when I wrote this. I'll have a look, but I did not get to templates yet. I restarted reading the tutorials about at the new year, because I stopped reading for quite some time and had to recap. I never read further that Chapter 9's comprehensive quiz.

> Well, yeah, of course C++ would implicitly convert the int -1 to an unsigned int...

It wasn't obvious to me!! But yeah, infinite loops suck. One good thing about them though is it alerts you to a problem, whereas an incorrect result might go undetected - probably doesn't matter for the kind of things we're programming, but could be disastrous in something like aircraft software!

Templates (and virtual functions) are pretty fun when you get to them, once you wrap your head around the syntax. It's basically like a souped up version of overloading, but the compiler does some of the hard work for you.

Thanks for the kind words!

Using an unsigned parameter violates the "don't use unsigned integers except for bit-level operations", and also the "don't use unsigned values just to avoid negative numbers" rule (not sure if I've made that one explicit, I'll check and make sure I have).

The correct solution here is to use a signed parameter, but then use an assert or other precondition (in C++20, expects) to validate that the value actually is negative.

As David correctly notes, you'll still get conversions if you pass in a signed value as the parameter.

@Alex, while I agree with your rules, I disagree that using an unsigned int is breaking them. Here is the function so you don't have to scroll up to see it:

and here is my proposed change with clarifying comments:

You would still need to assert the exp argument is not negative, but even if you do that, an unsigned int is better because you are using it for bit-level operations. Else you might anyway get undefined behaviour, even if you ensure that exp >= 0.

We normally would choose unsigned for bit-level manipulation because we don't want surprises from the sign-bit. But:

1) Such surprises can't happen in this case -- if exp must be positive (which we can enforce via assert or templatization), then the sign bit should always be 0, and we only do right shifts, so the sign bit never has a chance to flip.

2) We're treating this value as a number, not a sequence of bits. The bit manipulation here is an optimization, not a necessity (we could have used arithmetic instead, it just would have been slower).

Given the above, I'd still favor signed because then we can detect/handle the case when the caller passes in a negative value (even though the sample code doesn't, for simplicity), whereas with unsigned we can't (and we get a silent failure -- the worst kind).

Ok, so do I understand correctly that bitshifts on signed positive integers (sign bit = 0) is defined? It is just the bitshifts with negative integers which exhibit undefined behaviour. (Some compilers pad with 0s and other compilers pad with 1s when you shift a signed int with a 1 in the sign bit to the right?)

Also, is bit operations with positive signed integers defined by the C++ language standard, or is it just a case of everybody agrees on how they should work, even if it isn't defined?

Yes, I believe bit operations and binary representation for positive integers (and zero) are well defined by the C++ specification. It's only negative numbers that have issues, due to the fact that they can be encoded in different ways.

You are correct. I looked it up here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf It is in Chapter 5.8.

Bitshifts are defined by the standard for unsigned ints and non-negative signed ints as long as the result can be represented in the left operand's data type. For negative ints, the result is implementation-defined.

So I gave myself a challenge to write a geometric sequence and then display the last number in the sequence and state whether it's even or odd.

1. Is there any way I can improve this

2. I'm beginning to understand while loops. How do I do this:

if the user inputs a decimal number for "Enter a power: ". It'll output an speech and loop them back to question "Enter a power: " again until they give an integer without decimal point.

Hi Rai!

1.

* Initialize your variables with uniform initialization

* Line 32: You can use single quotation marks to make your numbers more readable (1'000'000)

* Line 32: This loop could be infinite if @power <= 1

* Use double numbers when calculating with doubles (1.0 instead of 1 etc.)

2.

Thanks. One thing. You told me about Initialize your variables with uniform initialization before but I don't understand what this means - how to use {} to initialize variables. Could you show an example.

This is part of lesson 2.1. Unfortunately, Alex doesn't use uniform initialization himself in most of the lessons.