Search

1.10 — Introduction to expressions

Expressions

Consider the following series of statements:

Each of these statements defines a new variable and initializes it with a value. Note that the initializers shown above make use of a variety of different constructs: literals, variables, and operators. Somehow, C++ is converting each of these literals, variables, and operators into a single value that can be used as the initialization value for the variable.

What do all of these have in common? They make use of an expression.

An expression is a combination of literals, variables, operators, and explicit function calls (not shown above) that produce a single output value. When an expression is executed, each of the terms in the expression is evaluated until a single value remains (this process is called evaluation). That single value is the result of the expression.

Here are some examples of different kinds of expressions, with comments indicating how they evaluate:

As you can see, literals evaluate to their own values. Variables evaluate to the value of the variable. We haven’t covered function calls yet, but in the context of an expression, function calls evaluate whatever value the function returns. And operators let us combine multiple values together to produce a new value.

Note that expressions do not end in a semicolon, and cannot be compiled by themselves. For example, if you were to try compiling the expression x = 5, your compiler would complain (probably about a missing semicolon). Rather, expressions are always evaluated as part of statements.

For example, take this statement:

If you were to break this statement down into its syntax, it would look like this:

Type could be any valid type (we chose int). Identifier could be any valid name (we chose x). And expression could be any valid expression (we chose 2 + 3, which uses 2 literals and an operator).

Key insight

Wherever you can use a single value in C++, you can use an expression instead, and the compiler will resolve the expression down to a single value.

Expression statements

Certain expressions (like x = 5) are useful by themselves. However, we mentioned above that expressions must be part of a statement, so how can we use these expressions by themselves?

Fortunately, we can convert any expression into an equivalent statement (called an expression statement). An expression statement is a statement that consists of an expression followed by a semicolon. When the statement is executed, the expression will be evaluated (and the result of the expression will be discarded).

Thus, we can take any expression (such as x = 5), and turn it into an expression statement (such as x = 5;) that will compile.

Note that we can make expression statements that compile but are meaningless/useless (e.g. 2 * 3;). This expression evaluates to 6, and then the value 6 is discarded.

Rule

Values calculated in an expression are discarded at the end of the expression.

Quiz time

Question #1


What is the difference between a statement and an expression?

Show Solution

Question #2


Indicate whether each of the following lines are statements that do not contain expressions, statements that contain expressions, or are expression statements.

a)

Show Solution

b)

Show Solution

c)

Show Solution

d) Extra credit:

Show Solution

Question #3


Determine what values the following program outputs. Do not compile this program. Just work through it line by line in your head.

Show Solution


1.11 -- Developing your first program
Index
1.9 -- Introduction to literals and operators

156 comments to 1.10 — Introduction to expressions

  • 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. :)

      • Ylva

        Yeah, and what about "==" ?
        I thought it would be better to store them in strings and then just write the condition for each... but I know nothing about single character type of information so cannot compare.

  • 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

  • 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.

  • 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

  • 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?

  • 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 :)

  • 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.

  • 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.

  • Josh

    Why don't include "Conditional ternary operator" ?

  • 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.

  • 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!!!

  • 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!!

  • benjamin

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

  • sumo1700

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

  • iris

    awesome job alex!

  • yoge

    very good tutorial......thank u so much

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

  • 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!

  • 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!

  • Insert Name Here

    Most easy to understand tutorial I have come across

  • 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)

    :D

    • 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.

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

  • 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. :)

  • 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.

  • 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

  • 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

  • Qian

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

  • 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

  • Simple yet to the point.

Leave a Comment

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