Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

รูปแบบเขียน Logical Operators แบบตัวอักษรใน C++

Logical Operators แบบเขียนเป็นคำ (Alternative Tokens)

ใน C++ มี keywords ที่ใช้แทนสัญลักษณ์ logical operators ได้ เรียกว่า Alternative Tokens ใช้ได้ตั้งแต่ C++98 มาจาก C ที่คีย์บอร์ดเก่าอาจไม่มีสัญลักษณ์บางตัว

ตารางเปรียบเทียบ

OperatorSymbolKeyword (Alternative Token)
Logical AND&&and
Logical OR||or
Logical NOT!not
Not Equal!=not_eq
Bitwise AND&bitand
Bitwise OR|bitor
Bitwise XOR^xor
Bitwise AND Assignment&=and_eq
Bitwise OR Assignment|=or_eq
Bitwise XOR Assignment^=xor_eq
Complement (Bitwise NOT)~compl

ตัวอย่างการใช้งาน

#include <iostream>
using namespace std;

int main() {
    int x = 1, y = 0;
    
    cout << "Alternative tokens for logical operators:\n";
    cout << x << " and " << y << " = " << (x and y) << endl;
    cout << x << " or " << y << " = " << (x or y) << endl;
    cout << x << " bitand " << y << " = " << (x bitand y) << endl;
    cout << x << " not_eq " << y << " = " << (x not_eq y) << endl;
    cout << "not " << x << " = " << (not x) << endl;
    cout << "compl " << x << " = " << (compl x) << endl;
    
    return 0;
}

ผลลัพธ์

Alternative tokens for logical operators:
1 and 0 = 0
1 or 0 = 1
1 bitand 0 = 0
1 not_eq 0 = 1
not 1 = 0
compl 1 = -2

ข้อดีและข้อเสีย

ข้อดี (Pros)

  • Readability - อ่านง่ายขึ้น โดยเฉพาะคนไม่คุ้นเคยสัญลักษณ์
  • Keyboard compatibility - ใช้ได้กับคีย์บอร์ดที่ไม่มีสัญลักษณ์พิเศษ
  • Searchability - ค้นหาในโค้ดง่ายกว่า (ค้นหา "and" แทน "&&")

ข้อเสีย (Cons)

  • Whitespace required - ต้องมี space ระหว่าง operand และ operator (เช่น a and b ไม่ใช่ a andb)
  • Less common - โปรแกรมเมอร์ส่วนใหญ่คุ้นเคยสัญลักษณ์มากกว่า
  • Inconsistent style - ผสมกับสัญลักษณ์เดิมอาจสับสน
  • Macro issues - อาจชนกับ macro names

Header <ciso646>

ใน C++98/03 ต้อง include <ciso646> เพื่อใช้ alternative tokens แต่ใน C++11 ขึ้นไป เป็น built-in keywords ไม่ต้อง include แล้ว

สรุป

Alternative tokens เป็นฟีเจอร์ที่น่าสนใจเพื่อ readability แต่ในทางปฏิบัติ สัญลักษณ์เดิม (&&, ||, !, !=, &, |, ^) ยังเป็นมาตรฐานที่ใช้กันกว้างที่สุด ควรเลือกใช้อย่างสม่ำเสมอภายในโปรเจกต์เดียวกัน