Giới thiệu
Từ khóa (Keyword) là từ dành riêng, có nghĩa cố định trong ngôn ngữ, không thể dùng làm tên biến. C có 32 từ khóa, C++ có thêm 30 từ khóa riêng.
Danh sách từ khóa C (32)
| auto | double | int | struct |
| break | else | long | switch |
| case | enum | register | typedef |
| char | extern | return | union |
| const | float | short | unsigned |
| continue | for | signed | void |
| default | goto | sizeof | volatile |
| do | if | static | while |
Từ khóa riêng C++ (30)
| asm | dynamic_cast | namespace | reinterpret_cast |
| bool | explicit | new | static_cast |
| catch | false | operator | template |
| class | friend | private | this |
| const_cast | inline | public | throw |
| delete | mutable | protected | true |
| try | typeid | typename | using |
| virtual | wchar_t | | |
Thuật toán
Nhập chuỗi str
Duyệt mảng keyword[32]:
Nếu strcmp(str, keyword[i]) == 0 → là từ khóa
In kết quả
Code C
#include <stdio.h>
#include <string.h>
int main() {
char keyword[32][10] = {
"auto","double","int","struct","break","else","long",
"switch","case","enum","register","typedef","char",
"extern","return","union","const","float","short",
"unsigned","continue","for","signed","void","default",
"goto","sizeof","volatile","do","if","static","while"
};
char str[] = "for";
int flag = 0, i;
for (i = 0; i < 32; i++) {
if (strcmp(str, keyword[i]) == 0) {
flag = 1;
break;
}
}
if (flag)
printf("%s is a keyword", str);
else
printf("%s is not a keyword", str);
return 0;
}
Kết quả
for is a keyword
Lưu ý
- Code gốc có lỗi gõ: "voltile" → sửa thành "volatile"
- Chương trình chỉ kiểm tra từ khóa C, chưa bao gồm C++
- Có thể mở rộng bằng cách đọc input từ bàn phím