1. 程式人生 > 實用技巧 >C語言成長之路26:複合賦值運算子

C語言成長之路26:複合賦值運算子

複合賦值運算子有以下幾個:

+=  -=  *=  /=  %=

而這種複合運算運算子,其實就想但與使用自身進行運算,如:

int number = 10;

number += 10; -->number = number + 10; //即20

注:

  1、複合賦值運算子的運算優先順序是14,遠低於普通的加減乘除;

  2、要記得定義的是變數,複合賦值是邊運算邊賦值,變數的值都取最後一步運算的結果,而不是最初定義的值;

以下是兩個例子:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <limits.h>
 4
5 void main(){ 6 /* C語言成長之路26:複合賦值運算子 7 * 複合賦值運算子有以下幾個: 8 * +=  -=  *=  /=  %= 9 */ 10 // 舉個例子:number += 10; 相當於number = number + 10; 11 int number = 10; 12 number += 10; 13 printf("number = %d",number); 14 15 // 練習1: 16 int a = 3; 17 int b = a += a -= a * a;
18 printf("\nb = %d,a=%d",b,a); 19 /* 過程: 20 * 1--> 由於*的優先順序比+= -= 大,所以先計算a*a = 3 * 3 = 9; 21 * 2--> 剩下的是a += a -= 9,從右邊往左計算,所以為a += (3 -= 9)則a 當前等於-6; 22 * 3--> 當前a= -6,b = -6 + -6 = -12; 23 * 4--> 由於b=a,所以最後結果a和b都是-12; 24 */ 25 };