bloggerads

2011年8月20日 星期六

C/C++ 的優先序


雖然到處都用括號括起來順序就一定不會錯,但是這樣寫code實在不方便閱讀
把優先序放在這邊方便參考

http://www.csee.umbc.edu/courses/104/fall06/burt/precedenceTable.html


LevelSymbolDescriptionAssociativity
1++
--
( )
[ ]
->
.
Prefix increment
Prefix decrement
Function call and subexpression
Array subscript
Structure pointer
Structure member
left to right
2!
~
-
+
(type)
*
&
sizeof
Logical negation
1's complement
Unary negation
Unary plus
Type cast
Pointer dereference
Address of
Size of
right to left
3*
/
%
Multiplication
Division
Modulus (integer remainder)
left to right
4+
-
Addition
Subtraction
left to right
5<<
>>
Bitwise left shift
Bitwise right shift
left to right
6<
<=
>
>=
Less than
Less than or equal to
Greater than
Greater than or equal to
left to right
7==
!=
Equal test
Not equal test
left to right
8&Bitwise ANDleft to right
9^Bitwise exclusive OR (XOR)left to right
10|Bitwise inclusive ORleft to right
11&&Logical ANDleft to right
12||Logical inclusive ORleft to right
13?:Conditional testright to left
14=
+=
-=
*=
/=
%=
<<=
>>=
&=
^=
|
Assignment
Compound add
Compound subtract
Compound multiply
Compound divide
Compound modulus
Compound bitwise left shift
Compound bitwise right shift
Compound bise AND
Compound bitwise exclusive OR
Compound bitwise inclusive OR
right to left
15,
++
--
Sequence point (list separator)
Postfix increment
Postfix decrement
left to right

2011年8月7日 星期日

C 函數指標的用法

C++有class, 那 C 呢??
以下介紹兩種方式,

方法一是定義的結構裡有函數pointer,然後再將結構宣告成陣列形式,好處是多定義了資料欄位


方法二是直接用陣列紀錄函式的pointer


//

// Method 1
//

+  int func1(int x)
+  {
+      return (2*x);
+  }
+  
+  int func2(int x) 
+  {
+      return (4*x);
+  }
+  
+  typedef struct 
+  {
+          int prio;
+          int ( *funcType )(int); //Function pointer
+  } TEST;
+  
+  int main()
+  {
+      
+      TEST MyTask[] =  {
+           { 1 , func1 },
+           { 2 , func2 }
+      };
+      
+      printf("x=2\n");
+  
+      printf("function priority = %d, output 2x= %d\n", MyTask[0].prio, MyTask[0].funcType(2) );
+  
+      printf("function priority = %d, output 4x= %d\n", MyTask[1].prio, MyTask[1].funcType(2) );
+      return 0;

+  }

--------------------------------Result----------------------------------


  x=2

  function priority = 1, output 2x=4
  function priority = 2, output 2x=8


//

//  Method 2
//

+  

+     void  Plus() {
+         printf("Plus\n");
+     }
+
+     void  Sub() {
+         printf("Sub\n");
+     }
+  
+     void main()
+     {
+         void ( *FuncGroup[] ) (void) = {Plus, Sub}; // 函數指標陣列
+
+         FuncGroup[ 0 ] (); // 呼叫函數
+         FuncGroup[ 1 ] ();
+     }

-----------------------------Result--------------------------------

  Plus
  Sub