Assertion (การยืนยัน) เป็นคำสั่งประกาศว่าเงื่อนไขต้องเป็นจริงเมื่อโค้ดทำงานถึงจุดนั้น
Assertions ช่วยตรวจสอบเงื่อนไขที่คาดหวัง
Simple Assertion
ใช้ assert(expression) จาก header assert.h
Syntax:
assert(expression)
ใน Simple assertion:
- เงื่อนไขเป็นจริง → ไม่มีการกระทำ
- พฤติกรรมเมื่อเท็จ ขึ้นอยู่กับ compiler flags
- Assertions เปิดอยู่ → เงื่อนไขเท็จทำให้โปรแกรมหยุด
- Assertions ปิดอยู่ → ไม่มีการกระทำ
Assertions ใช้จับข้อผิดพลาดภายในโปรแกรม (internal programming errors) เช่น ส่งพารามิเตอร์ผิด
ตัวอย่าง
โปรแกรม C Simple Assertion:
#include <stdio.h> #include <assert.h> int main(void){ int x; printf("Enter the value of x:\n"); scanf("%d",&x); assert(x >= 0); printf("x = %d\n", x); return 0; }
ผลลัพธ์
Run 1: Enter the value of x: 20 x = 20 Run 2: Enter the value of x: -3 Assertion failed! Program: G:\CP\CP programs\test.exe File: G:\CP\CP programs\test.c, Line 10 Expression: x >= 0