Search

1.5 — A first look at operators

Revisiting expressions

In lesson 1.1 -- Structure of a program, we had defined an expression as “A mathematical entity that evaluates to a value”. However, the term mathematical entity is somewhat vague. More precisely, an expression is a combination of literals, variables, functions, and operators that evaluates to a value.

Literals

A literal is a fixed value that has been inserted (hardcoded) directly into the source code, such as 5, or 3.14159. Literals always evaluate to themselves. Here’s an example that uses literals:

Literals, variables, and functions are all known as operands. Operands supply the data that the expression works with. We just introduced literals, which evaluate to themselves. Variables evaluate to the values they hold. Functions evaluate to produce a value of the function’s return type (unless the return type is void).

Operators

The last piece of the expressions puzzle is operators. Operators tell the expression how to combine one or more operands to produce a new result. For example, in the expression “3 + 4”, the + is the plus operator. The + operator tells how to combine the operands 3 and 4 to produce a new value (7).

You are likely already quite familiar with standard arithmetic operators from common usage in math, including addition (+), subtraction (-), multiplication (*), and division (/). Assignment (=) is an operator as well. Some operators use more than one symbol, such as the equality operator (==), which allows us to compare two values to see if they are equal.

Note: One of the most common mistakes that new programmers make is to confuse the assignment operator (=) with the equality operator (==). Assignment (=) is used to assign a value to a variable. Equality (==) is used to test whether two operands are equal in value. We’ll cover the equality operator in more detail later.

Operators come in three types:

Unary operators act on one operand. An example of a unary operator is the - operator. In the expression -5, the - operator is only being applied to one operand (5) to produce a new value (-5).

Binary operators act on two operands (known as left and right). An example of a binary operator is the + operator. In the expression 3 + 4, the + operator is working with a left operand (3) and a right operand (4) to produce a new value (7).

Ternary operators act on three operands. There is only one of these in C++, which we’ll cover later.

Also note that some operators have more than one meaning. For example, the - operator has two contexts. It can be used in unary form to invert a number’s sign (eg. to convert 5 to -5, or vice versa), or it can be used in binary form to do arithmetic subtraction (eg. 4 - 3).

Conclusion

This is just the tip of the iceberg in terms of operators. We will take an in-depth look at operators in more detail in a future section.

1.6 -- Whitespace and basic formatting
Index
1.4d -- A first look at local scope

63 comments to 1.5 — A first look at operators

  • Simple yet to the point.

  • Fuad Mannai

    This is the best tutorial I have come across. Well done and thank you very much for this valuble
    information about the C++. I wonder if you have tutorial for other languages such as C# and
    “Perl”, and “verilog”.

    Once again thank you very much
    Fuad Mannai

  • Qian

    Thank you very much, this is an awesome tut. I learned so much already.

  • Adam

    First of all, very good tutorial, I’m new to programming and was thinking of buying a book until I came across this on Google. And second, what is an example of an operand? In the equation “1 + 2” would 1 be an operand?

    Adam

  • Shobhan

    I have read it till here now, and i iwent for my 2nd c++ practical lecture, what seemed like cm chinese lingo to me in the 1st lecture was all crystal clear!!!! this is the best!! undoubteldy

  • I must say that I searched for a walkthrough tutorial, and have gone through 10+ different sites…this is the easiest to understand and the most in-depth one that I found…….

    MUCH THANX!!
    Nick M.

  • Koncept*

    You deserve an award of some kind for doing these tutorials! Trying to learn C++ to make coding for the iPhone (Cocoa Touc, Objective-C) easier to adjust to and this website is a allowing for an easier transition. 🙂

  • Alex……Your work is amazing for it was not for you i should be nowere in C++
    Thank you so much

  • peter

    hey i love the tutorials! very easy to follow.

    just one thought: correct me if im wrong but the - operator is always unary as 4 - 3 is essentially 4 + (-3)

    😀

    • Alex

      In C++, the - operator is implemented as both a unary operator and as a binary operator.

      When you write the expression x - y, you’re always invoking the binary form of the operator, with x and y as operands.

      • Casper

        In mathematical theory, the -- operator is always unary, but as far as I’ve gathered in terms of how the computer interprets the code, it uses the -- operator in a structurally similar way to the + operator. The computer just subtracts, it doesn’t separate the expression into adding a negative number.

        This is what I inferred from the lesson, not any expertise of my own, so I could completely be wrong, but that was what I understood.

  • Insert Name Here

    Most easy to understand tutorial I have come across

  • This is the best tutorial I have come across, pretty much everything is explained so well that I just get it and can play around with it easily. Thanks Alex!

  • Same thing everyone else has stated a thousand times before. This is an amazing tutorial and you are really putting this language into a context that even I, a high school student, can understand. I am an aspiring programmer and I would like you to know that you will be in my heart forever

    But seriously, thanks Alex!

  • I am beginner in c++ it is helping me very much.

  • yoge

    very good tutorial……thank u so much

  • iris

    awesome job alex!

  • sumo1700

    awesome……….. hurray…………..!!!!!!!!!!

  • benjamin

    wow im learning so much from you thanks alex!!!!!!!

  • wants2baDev

    I just want to thank you very much for taking your time and effort to put this walkthrough together. I have been working very hard on becoming a decent coder in multiple languages and this is one of the better walkthroughs I have come across. I can’t wait to finish this off before I go to school and try to become a game dev (long shot I know) but I am going to work my ass off to try!!

  • IgotaCinC

    Hats off to you Alex !!! The best tutorial I have ever come across. I never was a good programmer, just took C language in college and got a “C” in C :))
    I just never had a flair for programming and kept away from it as much as possible, but recently my interest in micro controllers just rekindled the hope of learning C again. You DA MAN!!! I am totally amazed at myself today that I am still sitting in front of my PC at 3am in the night going thru your tutorial and enjoying it to the bones. Excellent work!!!

  • Catreece

    <I> More precisely, an expression is a combination of literals, variables, functions, and operators that evaluates to a value.</i>

    Sooo… anything that spits out a number at the end? =P

    I have to ask though… if we have a function that uses the text based literals, such as "Hello, world!", and it returns 0 (zero) to state that it worked correctly, does that count as an expression?

    I suppose there's a few questions there, so lemme try this another way:

    1: Does the return of 0 count as an expression since it's outputting a value at the end?
    2: If a statement/function doesn't actually change the values of anything, is it still an expression even if it outputs a value?
    3: Is 0 a special case scenario that may not count as an actual value?
    4: Do boolean gates count as expressions?

    As far as I understand it, the expression has to actually change something somehow, so just displaying "Hello, world!" doesn't really count as much of anything since there's no number being changed. It can't be added to or altered really, at least not in a mathematical sense, without altering the nature of the literal in the first place, such as by converting it into numbers.

    If a boolean argument was made, though, such as the AND gate, where let's say… it's looking for both "hello" and "world", and if it gets both it spits out a 1 value, would that count as an expression in that case since it's actively converting a written literal into an output value? And if that's the case… does that mean booleans are operators?

    Sorry for being so nitpicky about such, I just can't help it when I run into potential exceptions to a rule or things which don't fit nicely into definitions. It always makes me question what their nature is and how to apply them. I suppose it matters less in this case since it's mostly just a matter of naming conventions, but I wanna knoooow! =P

    Anyway, thanks as usual for such a handy tutorial and clean/clear definitions! (most of the time, except when some jerk like me comes along and tries to break it in every way possible =P )

    • Alex

      > Sooo… anything that spits out a number at the end? =P

      Not just a number, could be any kind of data (e.g. a string, boolean, a class, a function, etc…). That’s why the definition uses the term “value”.

      The C++ standard defines an expression as “a sequence of operators and operands that specifies a computation”. I don’t particularly like that definition since literals don’t really specify a computation in my mind. They just are.

      Wikipedia has a pretty intuitable definition: “An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces (returns, in a stateful environment) another value. This process, like for mathematical expressions, is called evaluation. The value can be of various types, such as numerical, string, and logical.”

      > I have to ask though… if we have a function that uses the text based literals, such as “Hello, world!”, and it returns 0 (zero) to state that it worked correctly, does that count as an expression?

      Yes, the return value of a function could be part (or all) of an expression.

      Note: Expressions do not have to change something. 2+2 is an expression, and it evaluates to 4, but it doesn’t change anything. 4 is a literal expression, and it evaluates to 4, but it doesn’t change anything.

      Now, that value could be assigned to a variable, which would then change something, but that’s up to the developer.

  • Josh

    Why don't include "Conditional ternary operator" ?

  • James

    Thank you, Alex for encouraging me to learn programming. All hope about programming was lost, but now found. Once again, many thanks to Alex, all the people behind this website as well as the participants. The tutorials are very well explained, educative questions and comments from the participants and well coordinated responses. God bless you all.

  • Why u use void?
    it doesn’t return any value as far as i learnt earlier.
    Please explain the logic.

    • Alex

      (comment updated 6/20)

      Void is used in two different ways:
      * As a function return value to indicate that the function does not return any parameters.
      * As a function parameter to indicate that the function does not take any parameters. However, in C++ it’s considered better style to use an empty parameter list for this.

      I’ve amended the lesson to remove the use of void as a function parameter.

  • Devashish

    The the link “Introduciton to programming” is pointing to 1.1 Structure of a program. I am talking about the first sentence in this section. The is no section named Introduction to programming. Update the link text and it’s address. BTW..great tutorials Alex 🙂

  • nick

    Thanks for these sick ass guides bro.

    Some of the best material ive ever seen. The way all of it written is informative but to the point. Do you use c++ as your primary language?

  • Bharat

    Thanks alex sir for this wonderful tutorials love u alot sir and god bless u. Im almost about to finish this tutorial. I want from u to help us to learn java or any other languages u r the best teacher sir. Want to learn languages only from u

  • Vishal

    Why literals have no representation in memory? Doesn’t they need space to get stored in memory?What do you mean by "representation in memory"?Elaborate.

    • Alex

      Poor wording on my part. I meant to say that you can’t take the address of a literal. I’ve removed the statement altogether, because it’s not particularly relevant at this point in time.

  • Does adding a return statement when it’s not needed degrade the performance (even if only very slightly)? Like at the end of a void function

  • Dipjyoti Saha

    can we create a variable which stores operators?? like "+" "-" "*" "/"
    assuming that the program is created to ask for an operator from the user. like a program written for a calculator

    • Alex

      You can’t store operators in a variable. However, C++ does support a data type for storing single character (e.g. ‘a’, ‘+’, ‘5’). You can use this to store the character that represents the operator you’re interested in.

      We talk more about character data types in lesson 2.7 -- Chars, and using chars as part of a calculator is a future quiz question. 🙂

  • Tristan Gybels

    Hey, Alex!

    Try to make a book of this!
    I would buy this big time! I’m sure you’ll make some big money with it 😉
    You only have to cut ‘n paste everything.

  • Sam

    Thanks for the tutorial. Very useful!

  • Alfred O.

    Alex, can you explain what a "Primary Expression" is? It’s a term I’ve started to run into since taking a break from learning C++. I come back, and now I’m seeing "Primary Expression," "Postfix Expression," and "l-value" and "r-value" has been appended with "x-value," "gl-value," and "pr-value." It’s like I fell through a hole in time-space and woke up in a different dimension. What the heck does all this new stuff mean? Things used to be so simple!

    • Alex

      Yeah, C++11 kind of made a mess of things due to move semantics. From http://en.cppreference.com/w/cpp/language/value_category:

      a glvalue is an expression whose evaluation determines the identity of an object, bit-field, or function
      a prvalue is an expression whose evaluation either computes the value of the operand of an operator (such prvalue has no result object), or initializes an object or a bit-field (such prvalue is said to have a result object). All class and array prvalues have a result object even if it is discarded.
      an xvalue is a glvalue that denotes an object or bit-field whose resources can be reused
      an lvalue is a glvalue that is not an xvalue.
      an rvalue is a prvalue or an xvalue.

      There are a bunch of examples of each on that page.

      But honestly, I wouldn’t sweat about any of them right now except lvalue and rvalue. You can learn about glvalues, prvalues, and xvalues if and when they become useful in some context that’s relevant to something you need to know.

  • Alfred O.

    Hey Alex, I’m curious about a few things I’m wondering you could tell me about, concerning expressions. The question itself isn’t too bad, it’s just difficult to word clearly and brief. After some research, I had come to this conclusion:

    When an expression evaluates, a temporary object (often called a "temporary") is created to hold the result. This object exists until the end of the full expression, and then it is discarded. If nothing is done with the result of an expression (i.e., the expression has no side effect) it is generally considered a waste.

    ^ Not entirely sure if this is true. This is how I envision an expression evaluating:

    int x = 0, y = 10, z = 15;
    x = y + z;

    1. x, y, and z "evaluate" but the order of such is not specified. A temporary object is created to hold each of their values.
    2. y (10) and z (15) evaluate to 25, another temporary object is created to hold this value.
    3. 25 is copied into x.
    4. All temporaries are destroyed, in the reverse order they were created in, when the statement (or expression?) ends. More specifically, a "destructor" is called for them, much like the destructor of a class object when it goes out of scope.

    It’s possible only one temporary is made, or none. I don’t actually know what the truth is, so I come to you 🙂 I had drawn the conclusion that ALL expressions discard their values in the end (the temporaries created) whether or not their result is used, but I could be-and probably am-wrong about that, too. This might at least explain why an l-value reference cannot bind to something like 5 + 5, but an r-value reference can, one of the reasons I was curious about how expressions are carried out by the machine.

    • Alex

      You’re on the right track. Expressions do create temporary values that are discarded if nothing is done with them. However, expressions do have specific orders in which they are evaluated -- we cover this in lesson 3.1.

      In the above case, y + z are evaluated first, producing temporary rvalue 25. Then operator= is called, and that value of 25 is assigned to variable x. Done.

      • Alfred O.

        Ah! I meant the operands themselves may not evaluate in a specified order (well, I mean not specified by the C++ language, so it is left up to the designers of the compiler itself to decide, or maybe the compiler chooses based on what is more efficient).

        I read something out of curiosity, which led to one thing, which led to another thing, and now I’m so far off my tracks I can’t remember how I got where I’m at, or where I was. I believe it was a wikipedia article on "Sequence Points," something I saw and took note of. According to that, all operands of expressions, and arguments of functions-which I guess could be thought of as arguments of the function call operator ()-aren’t guaranteed to evaluate in any specific order. Which is probably why something like:

        function(i = 5 + x, x = i++, ++y = y - x * i); // Who knows what the heck you’ll get???
        index[i++] = ++i; // I wouldn’t dare to do this anyway

        Some places call it "Order of Evaluation" instead of "Sequence Points." And even more confusing, I stumbled across this article while researching it: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r1.pdf

        Looks like they’re trying to change this issue in C++17. If they do, I’ll have to get used to that right after learning about it, LOL. I guess it’s better they keep improving C++, it’s probably worth the headache.

        P.S. When the assignment operator = assigns a value, is this value copied into the variable, or is it "bound" like a reference? Or is the temporary value created by evaluation always discarded, regardless of what happens at the end of an expression?

        Also, thank you for responding to me. And thank you for this web site! It’s made learning the language so much easier. I bought a few of the recommended books (recommended from Stack Oveflow) and they don’t really go out of their way to explain much. After going through a few chapters on this site, and THEN reading the book (not all of it, but one day), the book makes perfect sense, so that tells you a whole lot about how good this site is.

        • Alex

          Don’t worry about sequence points for now. As long as you avoid using a variable with side effects applied more than once in a single expression, you’ll be fine. I cover side effects in more detail in chapter 3.

          When you use assignment, the value is copied. C++ does support references as well -- we also talk about those in chapter 6.

          Any temporary values from expressions are discarded at the end of the expression. Whether you copy those values to a variable (via assignment or initialization) is your choice. We talk more about initialization and assignment in chapter 2.

          I think it’s great that you’re going off the rails and doing your own explorations. Just note that a LOT of your questions are probably covered in future lessons, so keep reading!

          The reason this site exists is because I found most books to be very difficult to understand if you didn’t already know what they were talking about. I try to assume you don’t know anything here. Additionally, this site has gone through a lot of refinement based on reader questions, thoughts, and feedback. That’s one advantage an online site has over a book!

  • Matt

    Possible typo under "Operators":

    "Note: One of the most common mistakes the new programmers make is to confuse the assignment operator (=) with the equality operator (==)."

    I think maybe you meant to write "that new programmers" instead of "the new programmers".

  • My dear c++ Teacher,
    Please let me comment that at the end of 6th line, "std::endl" should be added, as follows:

    With regards and friendship.

    • Alex

      To have nice output, I agree we’d want to output std::endl. But the point of this lesson is to talk about literals, so I’m trying to keep the example as simple and focused as possible.

  • manuel okeke

  • Andrew

    Alex, you are the man!!

    Quick question - in the code snippet in this lesson, would it be prudent to put "return 0;" before "}" just to be consistent with your style in previous lessons?

    Just a thought - don’t know if it has any merit.

    Best,
    Andrew

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter