Variable Swap: How to swap two variables without a temporary variable
The following is a method of directly changing the values of variables 'a' and 'b' without using a temporary variable. This example is written in JAVA, but as most languages support bitwise operations, using this method can reduce unnecessary variable declarations and potentially improve performance.
/*How to swap 'a' and 'b' without a temporary variable. ※^ operator (exclusive - returns true only when different)*/ int a = 1; // 0000 0001 int b = 2; // 0000 0010 a = a ^ b; // 0000 0001 ^ 0000 0010 = //Result : a=2, b=1;
However, for readability, it might be better to just use a temporary variable.
0 개의 댓글:
Post a Comment