Keywords and Identifiers in C++
In C++ programming, keywords and identifiers are fundamental concepts used to build programs.
Keywords are reserved words with predefined meanings, while identifiers are user-defined names given to variables, functions, and classes.
1. What are Keywords in C++?
Keywords are reserved words in C++ that have special meaning and cannot be used as identifiers.
These words are predefined by the language and are used to perform specific operations.
2. Common C++ Keywords
int, float, double, char, void if, else, switch, case for, while, do, break, continue class, public, private, protected return, const, static, virtual
3. What are Identifiers?
Identifiers are names given to variables, functions, arrays, classes, and other user-defined items.
They help identify different elements in a program.
4. Rules for Naming Identifiers
1. Must start with a letter or underscore (_).
2. Cannot start with a digit.
3. Cannot use keywords as identifiers.
4. Case-sensitive (age and Age are different).
5. No spaces allowed.
5. Examples of Identifiers
int age;
float salary;
int totalMarks;
char grade;
int 1age; // starts with digit
int class; // keyword
int total marks; // space not allowed
6. Naming Conventions
1. Use meaningful names (e.g., studentAge).
2. Use camelCase or snake_case.
3. Avoid single-letter names.
4. Use uppercase for constants.
7. Difference Between Keywords and Identifiers
Keywords: Reserved words with predefined meaning.
Identifiers: User-defined names.
8. Example Program
#include <iostream>
using namespace std;
int main() {
int age = 20;
cout << age;
return 0;
}
9. Common Mistakes
1. Using keywords as identifiers.
2. Starting identifiers with numbers.
3. Using spaces in variable names.
4. Using unclear names.
10. Best Practices
1. Follow naming conventions.
2. Keep names meaningful.
3. Avoid reserved keywords.
4. Use consistent style.
11. Practice Exercises
1. Identify valid and invalid identifiers.
2. Write a program using proper naming.
3. List 10 keywords in C++.
Conclusion
Keywords and identifiers are essential building blocks in C++ programming.
Understanding their usage and rules helps you write clean, readable, and error-free code.
Codecrown