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

นิพจน์ (Expressions) ที่ประเมินในภาษา C มีกี่ประเภท


นิพจน์ (Expression) คือการรวมกันของตัวดำเนินการ (Operators) และตัวถูกดำเนินการ (Operands)

Operand คือข้อมูลที่ดำเนินการ

Operator ทำการดำเนินการบนข้อมูล

ตัวอย่าง: z = 3 + 2 * 1 → z = 5

นิพจน์ (Expressions) ที่ประเมินในภาษา C มีกี่ประเภท

ประเภทของนิพจน์ (Types of Expressions)

ประเภทของนิพจน์ที่ประเมินในภาษา C:

  • นิพจน์หลัก (Primary Expressions) - operand ในนิพจน์นี้อาจเป็นชื่อ ค่าคงที่ หรือนิพจน์ในวงเล็บ เช่น c = a + (5 * b);

  • นิพจน์ต่อท้าย (Postfix Expressions) - ตัวดำเนินการอยู่หลัง operand เช่น ab+

  • นิพจน์นำหน้า (Prefix Expressions) - ตัวดำเนินการอยู่หน้า operand เช่น +ab

  • นิพจน์เดี่ยว (Unary Expressions) - มี 1 ตัวดำเนินการ 1 operand เช่น a++, --b

  • นิพจน์คู่ (Binary Expressions) - มี 2 operands 1 ตัวดำเนินการ เช่น a+b, c-d

  • นิพจน์สามตัว (Ternary Expressions) - มี 3 operands 1 ตัวดำเนินการ เช่น Exp1? Exp2: Exp3 หาก Exp1 จริง รัน Exp2 มิฉะนั้นรัน Exp3

ตัวอย่าง

โปรแกรม C สำหรับนิพจน์ที่ประเมินในภาษา C:

#include <stdio.h>

int main() {
    int a, b;
    a = 10;
    printf("Value of b is %d\n", (a == 1) ? 100 : 200); // ternary expression
    printf("Value of b is %d\n", (a == 10) ? 10 : 20); // ternary expression
    return 0;
}

ผลลัพธ์

เมื่อรันโปรแกรม จะได้ผลลัพธ์ดังนี้:

Value of b is 200
Value of b is 10