troubleshooting Question

C# Prefix and Postfix Operators

Avatar of Kevin
KevinFlag for United States of America asked on
C#
2 Comments1 Solution446 ViewsLast Modified:
Afternoon,

I'm trying to teach myself C# and can't seem to grasp the prefix and postfix operators. I'm learning from a book that does not give such a great explaination of it, I've looked online at serveral examples but still dont get it.

The book I'm following gives the below example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example2._12
{
    /* Uses the preifx and postfix incremental and decremental operators */

    public class Incremental
    {

        public static void Main()
        {
            int x = 5;
            int y = 5;
            int a = 3;
            int b = 3;
            int j = 7;
            int k = 7;
            int result = 0;

            j++;
            ++k;
            Console.WriteLine("EXAMPLE1 j = {0} and k = {1}", j, k);

            j--;
            --k;
            Console.WriteLine("EXAMPLE2 j = {0} and k = {1}", j, k);

            result = 3 + x++;
            Console.WriteLine("EXAMPLE3 result = {0} and x = {1}", result, x);

            result = 3 + ++y;
            Console.WriteLine("EXAMPLE4 result = {0} and y = {1}", result, y);

            result = 2 + a--;
            Console.WriteLine("EXAMPLE5 result = {0} and a = {1}", result, a);

            result = 2 + --b;
            Console.WriteLine("EXAMPLE6 result j = {0} and b = {1}", result, b);

        }
    }
}

The output of this is:

EXAMPLE1 j = 8 and k = 8
EXAMPLE2 j = 7 and k = 7
EXAMPLE3 result = 8 and x = 6
EXAMPLE4 result = 9 and y = 6
EXAMPLE5 result = 5 and a = 2
EXAMPLE6 result j = 4 and b = 2

I undertstand that in example 1 why j = 8 and k = 8 being both j and k have a value of 7 and that the j++ and ++k add a value of one to the value making it 8.

I understand that in example 2 why j = 7 and k = 7 being both j and k "now" have a value of 8 and the operator j-- and --k subtract a value of one to the value making it 7.

But i dont undertstand  where the results are coming from for examples 3 through 6.

Can anyone explain this as simple as possible please so that I can understand where these values are coming from?

Kindly advise,

Regards,
N
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros