Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre- & Post Increment in C#

I am a little confused about how the C# compiler handles pre- and post increments and decrements.

When I code the following:

int x = 4; x = x++ + ++x; 

x will have the value 10 afterwards. I think this is because the pre-increment sets x to 5, which makes it 5+5 which evaluates to 10. Then the post-increment will update x to 6, but this value will not be used because then 10 will be assigned to x.

But when I code:

int x = 4; x = x-- - --x; 

then x will be 2 afterwards. Can anyone explain why this is the case?

like image 878
Schweder Avatar asked Dec 20 '11 09:12

Schweder


People also ask

Why does pre mean?

a prefix occurring originally in loanwords from Latin, where it meant “before” (preclude; prevent); applied freely as a prefix, with the meanings “prior to,” “in advance of,” “early,” “beforehand,” “before,” “in front of,” and with other figurative meanings (preschool; prewar; prepay; preoral; prefrontal).

How do you use pre?

Pre- is used to form words that indicate that something takes place before a particular date, period, or event. ... his pre-war job.

What is pre English?

The West Germanic or Anglo-Frisian dialect from which English developed; (also occasionally) English before written records. Also more generally: any language which may be regarded as a forerunner of (modern) English.

What is pre and examples?

The prefix pre-, which means “before,” appears in numerous English vocabulary words, for example: predict, prevent, and prefix! An easy way to remember that the prefix pre- means “before” is through the word prevent, for when you come “before” something else to stop it from happening, you prevent it.


1 Answers

x-- will be 4, but will be 3 at the moment of --x, so it will end being 2, then you'll have

x = 4 - 2 

btw, your first case will be x = 4 + 6

Here is a small example that will print out the values for each part, maybe this way you'll understand it better:

static void Main(string[] args) {     int x = 4;     Console.WriteLine("x++: {0}", x++); //after this statement x = 5     Console.WriteLine("++x: {0}", ++x);       int y = 4;     Console.WriteLine("y--: {0}", y--); //after this statement y = 3     Console.WriteLine("--y: {0}", --y);      Console.ReadKey(); } 

this prints out

x++: 4 ++x: 6 y--: 4 --y: 2 
like image 63
Sebastian Piu Avatar answered Oct 18 '22 18:10

Sebastian Piu