C # self-increasing and self-subtraction operators

Source: Internet
Author: User
Tags expression

The increment operator + + adds 1 to the value of the variable, while the decrement operator--slows the value of the variable by 1. They are suitable for sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal and any type of enum. For example, assuming that the value of an integer x is 9, then the value after X + + is 10.

Note: The operands of the self-increment and decrement operators must be a variable, a property accessor, or an index indicator accessor, not a constant or other expression. 5++ and (x+), for example, are illegal. If the operand is an accessor, then the accessor must support both read and write.

The self-increment and decrement operators also have a prefix. For the prefix operator, followed by the principle of "first increase or decrease, after use", the suffix operator is just the opposite, is "first use, after the increase or decrease." We use examples to illustrate this problem.

Program Listing 7-7:

Using System;
Class Test
{public
  static void Main () {
    int x=5;
    int y=x++;
    Console.WriteLine (y);
    y=++x;
    Console.WriteLine (y);
  }
}

The first time is to use after the addition, so the output is 5, the second first added after the use, the output is 7.

Look at one more example.

Program Listing 7-8:

Using System;
Class Test
{public
  static void Main () {
    int x=5;
    Console.WriteLine (x + +) + (x + +) + (x + +));
    int y= (x + +) + (x + +) + (x + +);
    Console.WriteLine (y);
  }
}


The results of the program running are:
18
27

Readers may find it difficult to understand the results of the output. In fact, the process of compiling is this: The compiler first scans the entire expression, first the X's original value out, the expression solution, and then for each x to perform the + + operation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.