นิยาม
Unary operator ทำงานกับ operand เดียว สร้างค่าใหม่ รายการครบ:
| Operator | คำอธิบาย |
|---|---|
| Indirection (*) | Dereference pointer คืน l-value ที่ address |
| Address-of (&) | ได้ address ของ operand (function designator หรือ l-value) |
| Unary plus (+) | คืนค่า operand ต้องเป็น arithmetic type |
| Unary negation (-) | ทำให้ค่าเป็นลบ arithmetic type ผลลัพธ์ไม่ใช่ lvalue |
| Logical negation (!) | กลับความหมาย operand → bool |
| One's complement (~) | Bitwise NOT integral type |
| Prefix increment (++) | เพิ่ม 1 คืนค่าใหม่ l-value ไม่ใช่ const |
| Prefix decrement (--) | ลด 1 คืนค่าใหม่ l-value ไม่ใช่ const |
| Cast () | Explicit type conversion |
| sizeof | Compile-time size ของ operand |
| new | Dynamic memory allocation |
| delete | Deallocate dynamic memory |
Associativity: right-to-left
ตัวอย่าง: - และ Cast
#include <iostream>
using namespace std;
int main() {
int x;
float y = 1.23;
x = (int)y; // cast
x = -x; // unary negation
cout << x;
return 0;
}
ผลลัพธ์
-1
หมายเหตุ: เนื้อหานี้ซ้ำกับ ID 1004083471