C Identifiers & Naming Rules
In C, identifiers are names given to various program elements, such as variables, functions, arrays, and more. Identifiers are used to uniquely identify and access these program elements in your code. Here are the naming rules and conventions for identifiers in C:
Naming Rules for Identifiers
:
1.
Valid Characters: Identifiers can consist of letters (both uppercase and lowercase), digits, and underscores. They must start with a letter or an underscore. C is case-sensitive, meaning that uppercase and lowercase letters are treated as distinct characters.
Valid Identifiers:
-
myVariable
- '_value'
- 'count123'
Invalid Identifiers:
-
'123count' (starts with a digit)
- 'my-variable' (contains a hyphen, which is not allowed)
- 'myVariable@' (contains a special character)
2. Length Limitation: Identifiers can be of any length, but only the first 31 characters are significant. This means that the first 31 characters of an identifier must be unique, but additional characters beyond that limit are not considered when distinguishing between identifiers.
3. Reserved Keywords: You cannot use reserved keywords as identifiers. Reserved keywords are special words in C that have predefined meanings and cannot be used for naming your own program elements.
For example, you cannot use int
, while
, or if
as an identifier.
Naming Conventions for Identifiers:
1. Descriptive Names: Use descriptive and meaningful names for your identifiers to improve code readability and understanding. Choose names that reflect the purpose or content of the program element.
Example:
-
Good: 'totalAmount', 'userInput', 'calculateArea'
- Avoid: 'x', 'a', 'func'
2. Camel Case: For multi-word identifiers (such as variable names and function names), use camel case or underscores to separate words. Camel case starts each word with an uppercase letter except the first one.
Examples:
-
Camel Case: 'myVariableName', 'calculateAreaOfCircle'
- Underscore: 'my_variable_name', 'calculate_area_of_circle'
3. All Uppercase for Constants: When defining constants (e.g., using #define), use all uppercase letters with underscores to separate words. This convention makes constants stand out and easily identifiable in your code.
Example:
#define MAX_VALUE 100
4. Avoid Single-Letter Names: Except for loop counters or very short-lived variables, avoid single-letter variable names as they are often not descriptive.
Example:
-
Good: 'i' (for a loop counter)
- Avoid: 'x', 'y', 'z'
5. Consistency: Be consistent in your naming conventions within your project or team. If a particular style or convention is already in use, follow it to maintain consistency.
In summary, following consistent and meaningful naming conventions for identifiers in your C code is essential for code clarity, readability, and maintainability. It helps you and other developers understand the purpose and usage of program elements, making it easier to work with and debug your code.