📜  增减运算符之间的区别

📅  最后修改于: 2021-05-30 04:06:19             🧑  作者: Mango

诸如C / C++ / Java之类的编程语言具有递增和递减运算符。这些是非常有用且常见的运算符。

  1. 增量运算符:增量运算符用于递增表达式中变量的值。在Pre-Increment中,值首先递增,然后在表达式内部使用。而在Post-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中,值首先递减,然后在表达式内部使用。而在Post-Decrement中,值首先在表达式内部使用,然后递减。

    句法:

    // 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等的更多准备工作,请参阅“完整面试准备课程”