ตรวจสอบว่าสตริงที่ให้มาเป็น Keyword ของ C/C++ หรือไม่ โดยเปรียบเทียบกับรายการ 32 คำสงวนของ C และ 30 คำเพิ่มของ C++
Keywords ของ C (32 คำ)
auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while
โค้ดตัวอย่าง
#include <stdio.h>
#include <string.h>
int main() {
char *kw[] = {"auto","break","case","char","const","continue","default","do",
"double","else","enum","extern","float","for","goto","if",
"int","long","register","return","short","signed","sizeof","static",
"struct","switch","typedef","union","unsigned","void","volatile","while"};
char str[] = "for";
int found = 0;
for (int i = 0; i < 32; i++)
if (strcmp(str, kw[i]) == 0) { found = 1; break; }
printf("%s is %sa keyword\n", str, found ? "" : "not ");
return 0;
}
ผลลัพธ์
for is a keyword