C Identifiers

Identifiers in C are names used to identify various elements such as variables, functions, arrays, structures, unions, and labels. They consist of letters (both uppercase and lowercase), digits, and underscores. However, an identifier must start with a letter or an underscore, and cannot start with a digit.

Rules for Constructing C Identifiers

1. Starting Character: The first character must be either a letter (a-z, A-Z) or an underscore (_). It cannot start with a digit.

2. Subsequent Characters: After the first character, identifiers can include letters, digits (0-9), or underscores.

3. Case Sensitivity: Identifiers are case-sensitive. For example, Variable, variable, and VARIABLE are different identifiers.

4. No Special Characters: Identifiers cannot contain special characters like @, #, +, etc.

5. No Spaces: Identifiers cannot include spaces.

6. No Reserved Words: Keywords (e.g., int, char, if) cannot be used as identifiers.

7. Length: Typically, identifiers should not exceed 31 characters in length, though this may vary by compiler.

Valid Identifiers:

total, sum, average, _m, sum1, my_variable

Invalid Identifiers:

3age // Starts with a digit
int // Reserved keyword
char // Reserved keyword
x+y // Contains a special character '+'

Types of Identifiers

1. Internal Identifier: Used for identifiers that are local to a function or block. These are often local variables or function parameters.

Example:

void exampleFunction() {
int localVar; // 'localVar' is an internal identifier
}

2. External Identifier: Used for identifiers that are visible across multiple files. These are usually global variables or function names.

Example:

int globalVar; // 'globalVar' is an external identifier

void exampleFunction() {
// Function 'exampleFunction' is an external identifier
}

Differences Between Keywords and Identifiers

Keyword Identifier
Pre-defined word User-defined word
Must be lowercase Can be uppercase or lowercase
Meaning is predefined Meaning is defined by the user
Combination of letters Combination of letters, digits, and underscores
Does not contain underscore Can contain underscores

Example:

int main() {
    int count = 10; // 'count' is an identifier
    char name = 'A'; // 'name' is an identifier

    // 'int' and 'char' are keywords
    // 'count' and 'name' are identifiers

    return 0;
}