# C語言解釋 - 運算子 Coding Style ###### tags: `c` # 運算子 (operator) ```clike= int a = 5; // assignment.將數字5指定給變數a int b = 3; if(a==b) { // equal. 運算子,判斷左右兩邊是否相同。 printf("A match B\n"); } else { printf("It's different between A, B\n") } ``` 在C語言裡,一個等號是指定的意思,把右邊的值指定給左邊變數;如果是兩個等號,就是比較運算子,判斷左右兩邊是否相同。 [cplusplus Operators](https://cplusplus.com/doc/tutorial/operators/) 我們會叫這些運算符號為`operator(運算子)`, 有熟悉的`+`, `-`, `*`, `/`, 還有比較運算子 `==`, `>` , `<` 等。詳情可見上方連結。 ```clike= if(a=b) { // 容易誤寫成指定運算子 printf("A match B\n"); } else { printf("It's different between A, B\n"); } ``` 剛開始學的時候,很容易把比較運算子`==`,寫成指定運算子`=`,指定運算子運算完結果會一直為真,會讓`if...else`一直為真。這種錯誤不容易被編譯器抓到,會讓人找問題找半天。 認識各種運算元後,還要知道其優先序,類似數學上的**先加減,後乘除**. ```clike= int A = 5 + 7 % 3; int B = 5 + (7 % 3); int B = (5 + 7) % 3; ``` 這邊我用`+`加法運算子以及`%`取餘數運算子,在我不確定餘數運算子優先於加法運算法,安全的方式是用圓括弧將想優先運算的部份先圈起來,這樣可以保證編譯器優先處理。 或是說這個算式是需要先執行加法,再將加法後的結果取餘法,這邊一樣,也是圓括弧包住加法運算。 # Coding Style ```clike if(a==b) printf("A, B match\n"); if(a==b) printf("A, B match\n"); if(a==b) { printf("A, B match\n"); } ``` 簡單來說,上述三種方式都可以編譯成功。我們再看下述程式 ```clike= // 未縮排 indent for(...) { // do...something if(sorted(...)) { // do...something } else { for(...) { // do...something if(...) { // do...something } } // do...something } } ``` ```clike= // 縮排過後的程式. indent for(...) { // do...something if(sorted(...)) { // do...something } else { for(...) { // do...something if(...) { // do...something } } // do...something } } ``` 有經過縮排的程式,可讀性會比較好,尤其是這種內含好幾層的敘述,如果排頭都一致,閱讀上會蠻困難的。 這種空格,通常叫做縮排(indent),是為了程式閱讀方便而設計的,建議使用。如果不使用縮排,也是可以,只要邏輯正確,語法也沒變,其實一樣可以執行。 但程式是寫給別人用的,為了讓大家都容易閱讀,所以都會採用一定的格定來撰寫程式,當然也包括縮排。尤其是幾個大專案,如果要一起創作,勢必寫出來的程式碼格式要跟大家一致,簡單來說就是排版。 [GNU codeing Standards](https://www.gnu.org/prep/standards/standards.html) [Google C++ Coding Style Guide](https://google.github.io/styleguide/cppguide.html) [Linux kernal coding style](https://www.kernel.org/doc/html/v4.10/process/coding-style.html) 要讓你的創作容易被大家接受,要學習一般通用的排版方式來寫你的程式碼。
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.