2014年2月25日 星期二

C 語言 敘述 / C langage statement

C 語言 敍述
作者:許裕永(Darban

C 語言是以敍述為單位,合法的敍述編譯才會過。很多第一次接觸 C 語言的學習者,都會為了什麼時候要加‘;’傷腦筋。所以,了解什麼是合法的敍述?或者說了解那一些是合法的敍述?是初學者的首要工作。下面列出初學者應該先知道的敍述。

以樣式分類,敍述可以分為:
1.          單行敍述 / single line statement
單行敍述以‘;’結尾,每一個‘;’代表一個敍述的結束。如果是一個‘;’單獨存在也是合法的,稱之為空敍述。
2.          區塊敍述 / block statement
以‘{’開頭,以‘}’結束,用來集合一個以上的單行敍述為一個敍述。

以語法分類,敍述可以分為:
1.          宣告敍述 (declare):
A.         變數宣告 (declare variables
type identifier;
 // ‘,’ 隔開identifier 可宣告一個以上
or
type identifier = value;
B.         常數宣告 (declare constants
const type identifier = value; // ‘,’
隔開identifier 可宣告一個以上
C.         陣列宣告 (declare arrays
type identifier[array_length];
or
type identifier[]={value, value.......};
D.         函式原型宣告 (declare function phototypes
return_type identifier(argument_type);
 // ‘,’
隔開argument_type可宣告一個以上
E.          結構宣告 (declare structs
struct identifier {};
or
struct identifier{}nameA,nameB;
2.          指派敍述 (assignment):
將值指派給某一個變數的敍述。
= , += , -= , /= , *= , %= , ++, --
以上列運算符號撰寫的運算式,均為合法的指派敍述(二進位運算符號未列入)。其他運算符號撰寫之運算式,不是敍述。
3.          函式呼叫敍述(function calls):
function_name(argument_value);
*
若函式的 return_type void ,此敍述必須單獨存在,不可以是其他運算式或敍述的一部份。例:
system(“pause”);
or
exit(0);
*
若函式的 return_type 不是 void ,此敍述可以單獨存在,也可以是其他運算式或敍述的一部份。例:
int value = pow(2,8);
or
printf(“%f”, sqrt(81));
//
此範例須在檔頭輸入 #include <math.h>
4.          函式定義敍述 (function definition)
return_type identifier(argument_type argument_identifier)
{
  statement
  return; // only if return_type is a void
}
or
return_type identifier(argument_type argument_identifier)
{
  statement
  return value; // only if return_type is not a void
}
* argument_identifier
在宣告函式原型時為非必要,在此處則必要。
5.          流程控制敍述(flow control):
A.         if / if else
                                             i.                if (condition)
 statement
                                           ii.                if(condition)
 statement
else
 statement
*
這裡的 statement 可以是單行敍述或區塊敍述。很多人說是“若 if 後的敍述只有一行,則大括號可以省略”不能說不對,但其實是倒果為因的講法。
*
無論是那一種寫法,一個 if / if else 算是一個敍述。即使是 if else 的區塊敍述中還有 if / if else (所謂的巢狀 if),也只算是一個敍述。
*
所謂鏈結的 if else if 其是只是 else 中的 if ,只能算是 if else 敍述的變化寫法,不算是另一種 if 敍述的樣式。
B.         switch
switch(variable){
case constant_value:
  statement
  break;
.
.
.
default:
  statement;
}
C.         while
while(condition)
  statement
statement
可以是單行敍述或區塊敍述。
初學者常犯的錯誤是:
while(condition);
  statement
小括號後的 ‘;’ 代表一個空敍述。所以,這個程式的邏輯是:如果 while(condition) 的條件成立,要執行此空敍述。而接下來的 statement 反而和這個 while 無關了。
D.         do while
do
  statement
while(condition);
statement
可以是單行敍述或區塊敍述。
E.          for
for(assignment_statement ; condition_expression ;
 not declare statement )
  statement
statement
可以是單行敍述或區塊敍述。
6.          其他敍述
A.         continue
只可用於迴圈敍述中。
B.         break
可以於 switch 敍述及迴圈敍述中。

C.         return
搭配 return_type 是否為 void ,有:
return;

return value;
兩種寫法。
很多人誤以為若 return_type void 時,不可以有 return 敍述。這是錯誤的觀念;正確的觀念是 return 關鍵字後不可以有 value

沒有留言:

張貼留言