📜  递增和递减运算符之间的区别

📅  最后修改于: 2021-09-13 03:13:36             🧑  作者: Mango

C/C++/ Java等编程语言具有自增和自减运算符。这些是非常有用和常见的运算符。

  1. 增量运算符:增量运算符用于增加表达式中变量的值。在 Pre-Increment 中,值首先递增,然后在表达式中使用。而在后增量中,值首先在表达式中使用,然后递增。

    句法:

    // PREFIX
    ++m
    
    // POSTFIX
    m++
    
    where m is a variable
    

    例子:

    #include 
      
    int increment(int a, int b)
    {
        a = 5;
      
        // POSTFIX
        b = a++;
        printf("%d", b);
      
        // PREFIX
        int c = ++b;
        printf("\n%d", c);
    }
      
    // Driver code
    int main()
    {
        int x, y;
        increment(x, y);
      
        return 0;
    }
    
  2. 递减运算符:递减运算符用于递减表达式中变量的值。在 Pre-Decrement 中,value 首先递减,然后在表达式中使用。而在 Post-Decrement 中, value 首先在表达式中使用,然后递减。

    句法:

    // PREFIX
    --m
    
    // POSTFIX
    m--
    
    where m is a variable
    

    例子:

    #include 
      
    int decrement(int a, int b)
    {
        a = 5;
      
        // POSTFIX
        b = a--;
        printf("%d", b);
      
        // PREFIX
        int c = --b;
        printf("\n%d", c);
    }
      
    // Driver code
    int main()
    {
        int x, y;
        decrement(x, y);
      
        return 0;
    }
    

    自增和自减运算符的区别:

    Increment Operators Decrement Operators
    Increment Operator adds 1 to the operand. Decrement Operator subtracts 1 from the operand.
    Postfix increment operator means the expression is evaluated first using the original value of the variable and then the variable is incremented(increased). Postfix decrement operator means the expression is evaluated first using the original value of the variable and then the variable is decremented(decreased).
    Prefix increment operator means the variable is incremented first and then the expression is evaluated using the new value of the variable. Prefix decrement operator means the variable is decremented first and then the expression is evaluated using the new value of the variable.
    Generally, we use this in decision making and looping. This is also used in decision making and looping.
    想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程