Search

1.9 — Introduction to literals and operators

Literals

Consider the following two statements:

What are “Hello world!” and 5? They are literals. A literal (also known as a literal constant) is a fixed value that has been inserted directly into the source code.

Literals and variables both have a value (and a type). However, the value of a literal is fixed and can’t be changed (hence it being called a constant), whereas the value of a variable can be changed through initialization and assignment.

Operators

In mathematics, an operation is a mathematical calculation involving zero or more input values (called operands) that produces a new value (called an output value). The specific operation to be performed is denoted by a construct (typically a symbol or pair of symbols) called an operator.

For example, as children we all learn that 2 + 3 equals 5. In this case, the literals 2 and 3 are the operands, and the symbol + is the operator that tells us to apply mathematical addition on the operands to produce the new value 5.

Author's note

For reasons that will become clear when we discuss operators in more detail, for operators that are symbols, it is common nomenclature to append the operator’s symbol to the word operator.

For example, the plus operator would be called operator+, and the extraction operator would be called operator>>.

You are likely already quite familiar with standard arithmetic operators from common usage in mathematics, including addition (+), subtraction (-), multiplication (*), and division (/). In C++, assignment (=) is an operator as well, as are << (insertion) and >> (extraction). 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. There are also a number of operators that are words (e.g. new, delete, and throw).

The number of operands that an operator takes as input is called the operator’s arity (almost nobody knows what this word means, so don’t drop it in a conversation and expect anybody to have any idea what you’re talking about). Operators in C++ come in three different arities:

Unary operators act on one operand. An example of a unary operator is the - operator. For example, given -5, operator- takes literal operand 5 and flips its sign to produce new output value -5.

Binary operators act on two operands (known as left and right). An example of a binary operator is the + operator. For example, given 3 + 4, operator+ takes the left operand (3) and the right operand (4) and applies mathematical addition to produce new output value 7. The insertion (<<) and extraction (>>) operators are binary operators, taking std::cout or std::cin on the left side, and the item to output or variable to input to on the right side.

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

Note that some operators have more than one meaning depending on how they are used. For example, operator- has two contexts. It can be used in unary form to invert a number’s sign (e.g. to convert 5 to -5, or vice versa), or it can be used in binary form to do subtraction (e.g. 4 - 3).

Chaining operators

Operators can be chained together such that the output of one operator can be used as the input for another operator. For example, given the following: 2 * 3 + 4, the multiplication operator goes first, and converts left operand 2 and right operand 3 into new value 6 (which becomes the left operand for the plus operator). Next, the plus operator executes, and converts left operand 6 and right operand 4 into new value 10.

We’ll talk more about the order in which operators execute when we do a deep dive into the topic of operators. For now, it’s enough to know that the arithmetic operators execute in the same order as they do in standard mathematics: Parenthesis first, then Exponents, then Multiplication & Division, then Addition & Subtraction. This ordering is sometimes abbreviated PEMDAS, or expanded to the mnemonic “Please Excuse My Dear Aunt Sally”.

Author's note

In some countries, PEMDAS is taught as PEDMAS, BEDMAS, BODMAS, or BIDMAS instead.

Quiz time

Question #1


For each of the following, indicate what output they produce:

a)

Show Solution

b)

Show Solution

c)

Show Solution


1.10 -- Introduction to expressions
Index
1.8 -- Whitespace and basic formatting

64 comments to 1.9 — Introduction to literals and operators

  • Joseph Garza

    Thank you! Nice lesson.

  • Manuel Calzadillas

    Nice Lesson,
    Alex, Is there a book that I can take as reference in addition to your material?
    Regards

  • abrattic

    Isn't the value of a variable changeable? I can just type [code]x = 7[code] later and change the value to something else, so how is 5 a literal constant?

    • Julian Spencer

      I think he means the number 5 itself.

      If x = 5, x is the variable's name, and 5 is it's value.

      5 will always equal 5 basically. You can't reassign 5 to equal 6 or something.

      I might be wrong so don't take my word for it. I'm learning along with you.

  • Nader Elsarrag

    Literals and variables both have a value (and a type). However, the value of a literal is fixed and can’t be changed (hence it being called a constant), whereas the value of a variable can be changed through initialization and assignment.

    if literals have a value and a type, then isn't that an object, i.e. 5 is an object in memory? and that when u assign some var to 5, you're actually setting one object equal to another?

    from what i read in the comments, I'm not sure if literals are a type of data or just a name for a programming element

    • Alex

      > if literals have a value and a type, then isn't that an object, i.e. 5 is an object in memory? and that when u assign some var to 5, you're actually setting one object equal to another?

      Generally, the compiler keeps track of the type and value of a literal. It uses the type to do type checking, and typically embeds those values in the generated code. No object is created in most cases.

      There are a few exceptions to the rule (e.g. for string literals and const l-value references bound to literals).

      • Nader Elsarrag

        Wow, I didn't expect such a fast reply. Thank you, that makes perfect sense. And thanks for creating this awesome tutorial!!

  • Hi

    On PEMDAS/PEDMAS/BEDMAS/BODMAS/BIDMAS: it goes
    Grouping: Parentheses, Brackets, etc.
    Exponents: Exponents + Roots (Roots don't apply in C++)
    Multiplication and Division from left to right: The biggest mistake I see people make: Multiplication does NOT have to go before Division.  They are at the same level, and it goes left to right.
    Addition and Subtraction from left to right: Similar to above.

  • Vivian

    If a person who can modify the site is reading this, the PEDMAS part on solution 3 and the end of the lesson is an American term. If you could for the sake of others who may not know this, then adding the English version BEDMAS may reduce confusion.

    • Julian

      Thank you very much Math teacher. Btw, Brackets = B in BEDMAS or BEMDAS

      • Glowerworm

        and BODMAS means Bracket, Order, Division/Multiplication,Addition/Subtraction. Acronyms/Mnemonics are fine but sometimes (like in this case) I think they only further convolute what they represent. Acronyms only work when they are easy to remember or silly (hard to forget). PEDMAS is neither of these. I personally don't like it. It is just as easy to remember the order of operations without the acronym, because the acronym is no more obvious than the order of operations themselves.

  • Taki76

    Why are the insertion (<<) and extraction (>>) operators required in C++ when using cin and cout? Isn't it obvious what action have cin and cout to perform?

    • DL

      As far as I know, it's because you can use these operators multiple times. For example, the cout operator <<, can be used to concatenate multiple literals or values, at the same time you can use the cin >> multiple times on the same line to input multiple values. That way you can be sure when youre displaying data (<<) or inserting data (>>) whenever you see them on a long statement.

      Why they use << >> instead of other type of symbol, is, well, because the creators wanted that way. There might be a context for it when it was created.

  • P

    These ads are super distracting, they take up literally half the page sometimes. Anyway, I guess it's more training for work as a real programmer with distractions heh.

    Thanks for the website, don't mean to be ungrateful!

    • LlamaBoi

      They need the ads so they can earn money to pay for servers to host this website and for their needs....if they are distracting you just use an ad blocker.

      • Glowerworm

        By using an adblocker you are taking away from their revenue, though. Although they get no revenue if you don't click on an ad in the first place. So personally I see it as: either accept the ads or use a blocker and donate to them directly.

  • Anonymous

    Are literals also stored as objects in memory like variables, the only difference being that their values are not updatable?

    • nascardriver

      Literals can be placed directly in the binary code (That's fast), whereas variable usually live in another memory segment and have to be read first before being used.

      • Anonymous

        Does the compiler decide by itself how to store a literal, since it was mentioned that literals also have a type eg. 5.0 might be stored in the same "format" as a floating point variable while 5 might be stored in an integer "format". ?

        • nascardriver

          The compiler can do whatever it wants as long as it doesn't change the behavior. If it thinks storing something as an integer is better even though you said it's a double, and you're never using it as a double, the compiler can store it as an integer.

          For example

          compiles to

          The `mov eax, 24` is the return value.

          As you can see, even though we had 2 literals and one of them was a double, the compiler noticed that this calculation doesn't have to happen at run-time and that we don't need a double, so it calculated the result at compile-time and stored it in code as an integer.

  • Euphoria

    I understand the difference between a Literal and Variable, but I feel it should be clarified more clearly as it is not written as concise as it perhaps should be.

    "Literals and variables both have a value (and a type). However, the value of a literal is fixed and can’t be changed (hence it being called a constant), whereas the value of a variable can be changed through initialization and assignment."
    -This is confusing as defining a variable "int x" for example and initializing it with the value 5 would then mean the literal is the 5.
    However, a variable explained more simply cannot be a literal as they are not close to the same in terms of their definition. (Variable referencing a named object whereas literal referencing the inserted value by the programmer into the source code).

    Apples to oranges comparison was confusing to me.

    As many have stated before, I want to thank you for this tutorial and your continued work in providing updated information and answers the questions. I appreciate it more than I can show.

    • Danny

      The "Hello, World" and "5" are called literals because those are fixed value, which means that "5"is a fixed "5", not "4" or "3" or something else. The same goes for "Hello, World". The value "5" of "int x{5}" is a variable value manipulated by the variable x, which you can call the x to change its value later. You may still be confused but think of it like "5" and x are different elements

  • Is it appropriate to describe a literal with "unnamed value"?

    • Tiger Yu

      Not really. When you go further in the tutorials, would will learn about anonymous objects. Anonymous objects do not have a name, but they are not literals. Literals are called literals because they are written out literally.

  • insertion chaining operators

    I have a question regarding: binary operator << (insertion)

    1) If we have the following code, is it an example of chaining operators too?

    2) for the first operator <<, we have std::cout on the left and string literal on the right, how about the second operator <<?How its operands are defined and processed because the string literal is already considered for the first operator <<?

    3)Also is operator << in general processed from left to right or right to left?

    Thank you.

    • nascardriver

      1)
      Yes

      2)

      The first part returns `std::cout`.

      3)
      Left to right, but the individual parts are executed in an unspecified order, more on that later.

  • involving zero input value

    "In mathematics, an operation is a mathematical calculation involving zero or more input values (called operands) that produces a new value (called an output value). "

    Would you please give me an example of an operator that has zero operands?

    Thank you.

    • Alex

      Many architectures support an operation called a "no op", which is an operation that has no operands. It does nothing for one clock-cycle, and is often used for delays. See https://en.wikipedia.org/wiki/NOP_(code)

  • Ed

    (2+3)+4 this would equal 9

  • Igor B.

    I'm not a native English speaker, but arity term (even if it's new word) sounds like quite a good generalization for a row: UnAry, BinAry, TernAry.
    BTW, I've not said yet - thank you for the tutorial! So far it's great!

    • Glowerworm

      Most of English is like that. Look up Greek and Latin roots. Opt, Logy, Mis, And, Gyn, Metr, etc. All of these have meaning and are used in words constantly.

  • Vitaliy Sh.

    in <p>'s "You are likely already..."; "Binary ..."
    (+), (-), (*), (/), (=), (==), (<<), (>>).

    ** <code>?

  • Jim

    I'm not sure if this is a dumb question or not.

    But aren't the brackets and braces in C++ also considered operators?  Including ( ), { }, [ ].

    How are these signs treated in C++ $, %, ^,. ?
    I'm sure that you can always output the words dollar and percent instead.  The up-arrow (to the power of) could be extended out with multiplication> But I'm sure programmers have figured out how to do this in C++ by now.

    • nascardriver

      (), [], % and ^ are operators. ^ is a bitwise xor, not a power operation.
      {} isn't an operator. It's used for scoping and initialization.
      $ has no use in C++.

  • Marie Bethell

    Hi, I think there's a typo; "Consider the following two statement: ". There should be an s on the end of statement.

  • geekersquad

    what is operand?

  • Bella

    How can you identify the difference between literals and variables?
    I mean isn't a literal printed out the exact same way as a variable?
    How do we know the difference. You wrote here...

    "Literals and variables both have a value (and a type). However, the value of a literal is fixed and can’t be changed (hence - called a constant), whereas the value of a variable can be changed through initialization and assignment."

    std::cout << "Hello world!";
    int x{ 5 }; // you said “Hello world!” and 5 are literals.

    OKAY... you're saying "5" is a literal even though it has underwent the procedure of initialization by using { }.
    The "hello world" text, I understand can be viewed as both a literal and variable(data)
    but the - 'int x {5}' -  I don't understand.
    Is identifying the difference between literal and variable/ data important? As I'm struggling to understand this topic.

    • A literal is the value you write down in your code. 5 and "Hello world!" are literals, what you do with them doesn't matter. `x` is a variable.
      If you don't understand it, you'll probably get the hang of it as you go along.

      • Danny

        I have read in Microsoft C++ Language Reference and it says that literal is a programming element that directly represents value. I find this more convincing

  • Nice

    Thank you so much for this, man. It's really helpful and easy to understand

  • km

    Does this not turn 5 into a variable?? int x { 5 }
    I can change the value of x after this which means it's not a constant right?

  • Rutvik Kapade

    dude i really love you ,this is like a online c++ bible for me and its free and really easy to understand ,god bless you. I am a student and i dont earn ,but this is helping me alot. = ) thanks again!

  • Andu

    Hi,

    "For example, the plus operator would be called operator+, and the extraction operator would be called operator<<." Should be operator>> !?

  • This is sooooo useful Thanks SOOO much whoever made this <3

  • Henrique dos Santos

    It's PEMDAS, not PEDMAS according to https://en.wikipedia.org/wiki/Order_of_operations

    • Alex

      Acronym fixed! Thanks for pointing out the omission.

      • Walter

        The acronym works both ways, and I've heard PEDMAS myself. I think it might be a USA vs UK thing?

        • Alex

          Yeah, I learned PEDMAS, but I think PEMDAS is more common and better because "Please Excuse My Dear Aunt Sally" is an easy mnemonic.

          • PEDMAS, PEMDAS and BODMAS all work. Multiplication & division are actually done in the same order, similar to addition and subtraction.

          • In my school, I had learnt about BODMAS rule and that is what knew till date.
            I heard the acronym PEMDAS for the first time in this article.

            Yes, all these mmemonics are due to geographic reasons.
            (https://en.wikipedia.org/wiki/Order_of_operations)

            In the United States, the acronym PEMDAS is common. It stands for Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. PEMDAS is often expanded to the mnemonic "Please Excuse My Dear Aunt Sally".

            Canada and New Zealand use BEDMAS, standing for Brackets, Exponents, Division/Multiplication, Addition/Subtraction.

            Most common in the UK, Pakistan, India, Bangladesh and Australia and some other English-speaking countries is BODMAS meaning either Brackets, Order, Division/Multiplication, Addition/Subtraction or Brackets, Of/Division/Multiplication, Addition/Subtraction. Nigeria and some other West African countries also use BODMAS.
            Similarly in the UK, BIDMAS is also used, standing for Brackets, Indices, Division/Multiplication, Addition/Subtraction.

Leave a Comment

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