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

คำถามเกี่ยวกับ Comma Operator ใน C/C++


Comma Operator ใน C/C++ มี 2 บริบท คือ

  • เป็น Separator (ตัวคั่น)
  • เป็น Operator - ตัวดำเนินการคอมม่า { , } เป็น binary operator ที่ทิ้งนิพจน์แรก (หลังประเมินค่า) แล้วใช้ค่าของนิพจน์ที่สอง ตัวดำเนินการนี้มี precedence ต่ำสุด

พิจารณาโค้ดต่อไปนี้และทายผลลัพธ์

ตัวอย่างที่ 1

#include <stdio.h> int main(void) { char ch = 'a', 'b', 'c'; printf("%c", ch); return 0; }

ผลลัพธ์

เกิด error เพราะคอมม่าทำงานเป็น separator

prog.c: In function 'main': prog.c:5:20: error: expected identifier or '(' before 'b' char ch = 'a', 'b', 'c'; ^~~

ตัวอย่างที่ 2

#include <stdio.h> int main(void) { char ch; ch = 'a','b','c'; printf("%c", ch); return 0; }

ผลลัพธ์

ให้ a เป็น output เพราะคอมม่าทำงานเป็น operator แต่ precedence ต่ำกว่า assignment จึงได้ a

a

ตัวอย่างที่ 3

#include <stdio.h> int f1() { return 43; } int f2() { return 123 ; } int main(void) { int a; a = (f1() , f2()); printf("%d", a); return 0; }

ผลลัพธ์

ให้ 123 เป็น output เพราะคอมม่าในวงเล็บทำงานเป็น operator ประเมินนิพจน์ที่สอง

123