1

Well my English not very good and I am a beginner of C pls don't mind.Here's the questions , when I put in ++a and a-- at the same program ,the second always read the forward one , can someone help me to figure it out im will appreciate it.

#include<stdio.h>
#include<stdlib.h>

int main() {

   int a = 8;

   printf("a=%d\n", ++a);
   printf("a=%d\n", a--);

   system("pause");
   return 0;
}

it output a=9 a=9

jsn
  • 35
  • 5
  • 1
    `++a` increments `a` and then returns the value so the first output is `9` while `a--` will return the value of `a` first and then decrement it, so you still get `9` as the second output. – JASLP doesn't support the IES Jun 24 '21 at 06:45

3 Answers3

2

The placement of the increment or decrement operator (before or after) changes the semantics of the operation.

For the pre-increment and -decrement operator, the result is the new value (after increment or decrement).

For the post-increment and -decrement, the result is the old value (before the increment or decrement).

That means e.g.

printf("a=%d\n", a--);

is equivalent to:

{
    int old_value = a;
    a = a - 1;
    printf("a=%d\n", old_value);
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

That’s correct. The first printf pre-increments to 9 and then prints that. The second evaluates the 9, prints it, and then post-decrements.

Howlium
  • 1,218
  • 1
  • 8
  • 19
0

++a increments a first before printing. a-- prints a first before decrementing.

bg117
  • 354
  • 4
  • 13