The basics of programming in c++ for beginners

Increment and decrement in C ++

At previous article we are considered binary operators, which is used for arithmetic operations on two operands (variables). In this lesson we will learn how to apply the unary operators, that require one operand. they are called increment ( ++ ) and decrement (). The role of these operators in, in order to change (increase or decrease, respectively,) the value of a variable by one, and the value will be overwritten. Consider the example, which will change the value of a variable variable unit in three different ways:

After each operation in lines 11, 13 and 15. to the variable variable increased by one. As you can see, the shortest recording – a record with the increment. Below, in strings 17 – 19, We have applied three times decrement and eventually obtain the value variable reduced to 3.

Compile:

increment and decrement

Both unary operator can have two forms: postfix ( where the operator is located just behind the variable) and prefix (the operator is located in front of the variable). In this example, we used postfix increment and decrement. What is the difference between these forms from each other? Both the first and second forms of these operators perform the same role – increase or decrease of a variable by one. But if a line of code, where the increment or decrement is applied, present any further commands, whereas these operators in different ways behave. Postfix will be used after the other teams. Let's look at the following example,:

As a result of lines of code 12, we will see on the screen the number of 0. It happens because, that the increase in the unit will run after the withdrawal value of the variable variable the screen. To make sure, that the value really changed – in string 13 please show us variable. But in the case of the prefix form of increment (string 16), Variable overwritten directly and already only then will display. To decrement all the same, but with a reduction unit.

Compile:

increment and decrement

Here's a look at this example more:

Result:
increment and decrement

Try to understand, why as a result of a string of operations 11, variable a It became equal 10. Asking questions in the comments not prohibited.

80 thoughts on “Increment and decrement in C ++

  1. Помогите разобраться в задаче:
    x = y = 0;
    while ( Y < 10 ) x += ++ Y;
    printf (" x= %d y = %d\n", x, Y);

    Ответ x = 55 y = 10
    Я не понимаю как x получается 55. Прям голову сломала(((

    1. x=0+1=1
      x=1+2=3
      x=3+3=6
      x=6+4=10
      x=10+5=15
      x=15+6=21
      x=21+7=28
      x=28+8=36
      x=36+9=45
      x=45+10=55

      pervaya cifra eto zna4enie x a vtoraya cifra eto zna4enie y, vot i resultat, ++y srazu uveli4ivaet zna4enie y na 1

  2. x=0+1=1
    x=1+2=3
    x=3+3=6
    x=6+4=10
    x=10+5=15
    x=15+6=21
    x=21+7=28
    x=28+8=36
    x=36+9=45
    x=45+10=55

    pervaya cifra eto zna4enie x a vtoraya cifra eto zna4enie y, vot i resultat, ++y srazu uveli4ivaet zna4enie y na 1

  3. By the way, а почему получается число 10 , in string 11 ?? Я использую CodeBlock как среду. Вначале написал сам код, получил 9. Потом специально скопировал ваш и … again 9. Я так понимаю, что в процессе расчета,когда обрабатывается второй инкремент, он далее умножается на 2, а только после этого складывается с левой частью команды. Может объясните, why is that ? Или так и должно быть ? Тогда почему у вас 10? Да и вообще, алгоритм несколько не логичным выходит

  4. Такая последовательность вычислений?
    a = variable + 1 + ++variable * 2
    a = (2 + 1 + 2) * 2

    1. a=++variable + 1 + ++variable*2;
      a=(2+1+3)*2; \\ я все правильно понимаю?

      Тогда получается 12))

  5. Мне не понятно! Если считать правильно, то должно получиться 7, as – 2+1+2*2 = 7.
    But 10 получиться, если компилятор воспринял значения (2+1+2) как в скобках, а почему он так воспринял не понятно и как писать, что бы не воспринимал так!?
    А вот больше всего мне не понятнопочему в онлайн компиляторе вообще получается 9!? – я даже не понял как он так посчитал! Может кто-то объяснит?

  6. So, сейчас понял, что второй инкремент тоже увеличиваетсяно тогда в онлайн компилляторе правильно – 9, но почему 10 – вот не понятно!?

  7. I.e, на сколько я понял, компилятор сначала вычисляет variable.
    1. variable=1+1, присвоено 2.
    2. variable=2+1, присвоено 3.
    Теперь вычисляется а=3+1+3×2=10. So?

    1. точно не считал попрограммированию”, но как и считал 9 должно должно получитьсятак понялкак и в компилляторетут может опечатка или что-то вроде того….

      1. Проверил в 2-х онлайн компиляторах, та же петрушка, a=9. Но по идее должно быть 10,т.к приоритет у пре-инкремента 3 RL, а по сему сначала variable вычисляется, а потом уже он принимает участие в примере. И он по-любому равен 3, значит пример должен выглядеть так: а=3+1+3*2. Компиляторы же , apparently, считают последовательно, i.e.. а=2+1+3*2, тогда действительно получается 9. Но почему так?! Я что-то не допонял? Эх, кто бы объяснил подоходчивей.

  8. 2+1+2*2
    второй variable все еще хранит значение 1, в тот момент когда первый variable уже 2. но вот арифметика мне пока непонятна. умножение то должно выполняться первым.

Leave a Reply

Your email address will not be published. Required fields are marked *