Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to check if a given string is Keyword or not?
In C programming, a keyword is a predefined or reserved word that has a fixed meaning and is used to perform specific operations. The C language has 32 keywords that cannot be used as variable names or identifiers.
Syntax
int strcmp(const char *str1, const char *str2);
We can check if a string is a keyword by comparing it with all C keywords using the strcmp() function.
C Keywords
The following table lists all 32 keywords in the C programming language −
| 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 |
Example: Checking if String is a Keyword
The following program demonstrates how to check if a given string is a C keyword or not −
#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 == 1)
printf("%s is a keyword
", str);
else
printf("%s is not a keyword
", str);
return 0;
}
for is a keyword
How It Works
- We store all 32 C keywords in a 2D character array.
- We use the
strcmp()function to compare the input string with each keyword. - If a match is found, we set a flag and break out of the loop.
- Based on the flag value, we determine if the string is a keyword or not.
Conclusion
This program effectively checks if a given string matches any of the 32 C keywords using string comparison. The approach is simple and works by iterating through all keywords and comparing them with the input string.
Advertisements
