top

Search

C Tutorial

.

UpGrad

C Tutorial

Identifiers in C

When it comes to C programming, identifiers are a cornerstone that programmers cannot ignore. Identifiers refer to the names you give to entities such as variables, functions, and arrays to distinguish them in your code. This article will unravel the identifiers in C rules, types, scope, and more.

Introduction to Identifiers in C

In C programming, identifiers are the names assigned to different entities such as variables, functions, arrays, etc. Here's a simple code example:

int score = 90;

In this case, 'score' is an identifier that we've used to name our integer variable. There are several reasons why understanding identifiers is of paramount importance, especially in the C programming language. 

1. Enhanced Readability and Maintenance: Effective use of identifiers makes your code self-explanatory, thereby helping programmers understand the code's purpose without diving deep into its implementation. For instance, consider the following code snippets:

int v = 3.14 * r * r;

While this code is technically correct, it's not immediately apparent what 'v' and 'r' are. Now let's change the identifiers:

int area = 3.14 * radius * radius;

With the use of 'area' and 'radius', the purpose of the variables is immediately clear, leading to an increase in code readability. 

2. Debugging: Understanding identifiers and their rules can save a programmer from potential bugs. 

3. Adhering to Language Syntax: Each programming language has its set of rules and syntax, and identifiers in C are no exception. There are regulations concerning valid characters, length, and reserved keywords, which, if violated, would lead to compile-time errors.

4. Efficient Memory Use: The scope of an identifier (whether it is local, global, or static) impacts the memory allocation and deallocation, affecting the overall performance of the program. 

Rules for Naming Identifiers

Identifiers, as the name suggests, are utilised to identify various elements in a program, such as variables, functions, arrays, etc. The freedom of naming these identifiers as we see fit can seem empowering, but with great power comes great responsibility. The responsibility here lies in adhering to certain rules and conventions while naming these identifiers.

Let's examine these rules in greater depth.

Valid and Invalid Identifiers in C

The first rule while naming an identifier is that it must start with either a letter (lowercase or uppercase) or an underscore. The subsequent characters can be a mix of letters (a-z or A-Z), digits (0-9), or underscores (_). Identifiers must only contain alphanumeric characters.

For example:

int _score1; // Valid identifier
char myString; // Valid identifier

These identifiers adhere to the rules and will be accepted by the C compiler.

Contrary to valid characters, certain characters are not allowed in identifiers. These include special characters (e.g., $, @, #, %, etc.), spaces, punctuation, and identifiers that cannot start with a digit. Any identifier with these characteristics will be rejected by the compiler.

For instance:

int 123score; // Invalid identifier: starts with a digit
char student-name; // Invalid identifier: contains a special character

The C compiler will throw an error when it encounters these identifiers.

Length Restrictions for Identifiers

While the ANSI C standard does not impose a specific limit on the length of identifiers, some older compilers may have had limitations. Modern compilers generally support longer identifiers, and the actual maximum length can vary depending on the compiler and implementation. It is recommended to choose meaningful and concise identifiers without excessive length, following good coding practices.

int number_of_students_in_the_class; // Too long
int n; // Too short
int student_count; // Just right

Case Sensitivity in Identifiers

Identifiers are case-sensitive, meaning the same sequence of characters but with a different case is treated as a different identifier. Therefore, 'score' and 'Score' are two distinct identifiers in C. 

int score = 10;
int Score = 20;

printf("%d %d", score, Score); // Outputs "10 20"

As demonstrated, 'score' and 'Score' are treated as two different variables holding separate values.

Reserved Keywords in Identifiers

C language reserves certain words, known as keywords, for its syntax. These keywords carry special meanings for the compiler and, therefore, cannot be used as identifiers. Attempting to use such words as identifiers will result in a compilation error. Reserved keywords include int, char, for, while, if, etc.

int for = 10; // Invalid identifier: 'for' is a reserved keyword

The identifier rules in C act as a guide to naming identifiers correctly, facilitating the creation of clean, error-free code. 

Naming Conventions for Identifiers

While the rules for naming identifiers form the necessary foundation, naming conventions take a step further into the realm of good practices. Adhering to these conventions is widely regarded as a hallmark of high-quality, maintainable code.

Here are some widely adopted naming conventions in C:

1. Descriptive Names: Identifiers should accurately reflect the purpose of the variable, function, or other entity they're naming. For example, if a variable holds the age of a person, 'age' would be a more descriptive identifier than a vague name like 'a' or 'x'.

int age; // Good naming convention
int x; // Poor naming convention

2. Use of Underscores: Underscores can be used to separate words in an identifier, making it more readable. This is commonly known as snake_case.

int student_age; // Good naming convention
int studentage; // Harder to read

3. Case Sensitivity: Since C is case-sensitive, it's important to be consistent with the case you use for an identifier. It's easy to forget the case and inadvertently create or reference the wrong variable.

int score; // Consistent usage of lowercase
Score = 10; // Inconsistent - creates a new variable instead of assigning to 'score'

4. Avoid Abbreviations: Where possible, avoid abbreviations or make sure they're explained clearly in the comments.

int num_students; // Clear identifier
int num_stud; // Potentially confusing abbreviation

5. Consistency: Consistency is a key aspect of good naming conventions. If you're using snake_case for multi-word identifiers, stick to it throughout your code. If you're starting function names with a verb (like 'get_value', 'set_value'), do that for all your functions. Consistency makes your code much easier to navigate.

Types of Identifiers in C

In the realm of C programming, each identifier type plays a unique role in how the program operates; hence understanding these types is critical for efficient coding. Let's delve deeper into the types of identifiers in C:

1. Variable Identifiers: Variable identifiers refer to memory locations where values are stored and manipulated throughout the code. For instance:

int score = 100; // 'score' is a variable identifier

2. Function Identifiers: Function identifiers are names given to functions, which are blocks of code designed to perform specific tasks. The function identifier is used to call the function wherever its operation is needed.

void displayScore() {
    // Function code
}
// 'displayScore' is a function identifier

3. Array Identifiers: An array is a collection of elements of the same data type, and an array identifier is a name given to such an array. It represents the entire collection and can be used to access the individual elements.

int scores[5] = {90, 92, 88, 96, 94}; // 'scores' is an array identifier

4. Structure Identifiers: Structures in C are user-defined data types that group variables of different data types. A structure identifier refers to such a structure and can be used to access its member variables.

struct student {
    char name[50];
    int age;
}; // 'student' is a structure identifier

5. Union Identifiers: Unions are similar to structures, i.e., they group variables of different data types. However, in a union, all member variables share the same memory location. A union identifier names such a union.

union job {
    char name[50];
    int id;
}; // 'job' is a union identifier

6. Enumeration Identifiers: Enumerations, or enums, are user-defined data types that consist of integral constants. An enumeration identifier is a name given to such an enumeration.

enum week {Mon, Tue, Wed, Thu, Fri, Sat, Sun}; // 'week' is an enumeration identifier

7. Typedef Identifiers: Typedef is a keyword in C used to assign a new name to an existing data type. A typedef identifier is this new name, which can then be used in place of the original data type.

typedef unsigned long ulong; // 'ulong' is a typedef identifier
ulong size = 50000; // Using 'ulong' in place of 'unsigned long'

Keyword and Identifiers in C: Differences 

Keywords and identifiers in C are fundamental concepts which might seem similar, though they have distinct roles within a program and follow different rules and conventions.

A keyword is a predefined word that C reserves for a specific purpose. Keywords are part of the language syntax, and each keyword carries a special meaning to the C compiler. Examples of keywords include int, char, for, while, if, etc. You cannot use a keyword as an identifier in your program.

An identifier, on the other hand, is a name given by the programmer to a particular entity in the code, such as a variable, function, array, etc. Identifiers are not predefined and are created by the programmer. 

Let's compare the two using a table to outline their key differences:

Keyword

Identifier

Predefined in the C language.

Defined by the programmer.

Cannot be used as a variable name.

Used as names for variables, functions, arrays, etc.

Each keyword carries a special meaning and is used in specific contexts.

An identifier doesn't inherently have a special meaning and can be used as needed by the programmer.

Examples: int, float, return, for, while.

Examples: score, displayScore, student_age, week.

Scope of Identifiers

The scope of an identifier in a C program refers to the region of the program where the identifier is recognised and can be accessed. It denotes the visibility and lifetime of an identifier. The scope of an identifier is defined by where it is declared within the C code. 

Local Identifiers

A local identifier is declared within a function or a block and can only be accessed within that function or block. Once the execution leaves the function or block, the identifier ceases to exist. Hence, its scope is limited to the function or block where it's defined.

void display() {
    int score = 100; // 'score' is a local identifier
    printf("%d", score);
}

In the above example, the identifier 'score' is local to the function 'display'. It cannot be accessed outside this function.

Global Identifiers

A global identifier is declared outside all functions, typically at the top of the program. Global identifiers are accessible throughout the program from the point of declaration to the end of the program. They exist for the lifetime of the program.

int score = 100; // 'score' is a global identifier

void display() {
    printf("%d", score); // 'score' can be accessed here
}

In this example, 'score' is a global identifier and can be accessed within the function 'display' as well as anywhere else in the program.

Static Identifiers

A static identifier retains its value even after the execution leaves its scope. The 'static' keyword is used to declare such identifiers. A static identifier can be local or global, but its value persists between function calls.

void display() {
    static int count = 0; // 'count' is a static identifier
    count++;
    printf("%d", count);
}

In the function 'display', 'count' is a static identifier. Even though 'count' is a local identifier within the 'display' function, it retains its value between function calls due to the 'static' keyword.

Storage Class Specifiers

Storage Class Specifiers are used to control two fundamental properties of variables in C: scope (visibility) and lifespan (lifetime). These specifiers provide additional information about the variables and define how and where they should be stored in memory during program execution.

Storage Class Specifiers help communicate variable behaviour to the compiler, influencing storage location, duration, and access methods.

In the C language, there are four Storage Class Specifiers: auto, register, static, and extern. Let’s explore their unique purposes!

Automatic Storage Class

It is the default storage class for all local variables.

void myFunction() {
    auto int auto_var = 40; // 'auto_var' is an automatic identifier
}

Register Storage Class

It is used to define local variables that should be stored in a register instead of RAM.

void myFunction() {
    register int register_var = 50; // 'register_var' is a register identifier
}

Static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope.

void myFunction() {
    static int static_var = 60; // 'static_var' is a static identifier
}

Extern Storage Class

Extern storage class is used to give a reference of a global variable that is visible to ALL the program files.

extern int extern_var; // 'extern_var' is an extern identifier

Conclusion

Understanding and effectively using identifiers and keywords in C is vital for anyone looking to master this powerful and versatile programming language. Remember, the right identifier naming practices can make your code more comprehensible, maintainable, and robust.

If you want to dig deeper into C programming and other programming languages, check out upGrad's comprehensive courses, such as DevOps Engineer Bootcamp, designed for all levels of learners.

FAQs

1. What is an identifier in C?

An identifier in C is a name given to entities such as variables, functions, arrays, etc.

2. What are the rules for naming identifiers in C?

Identifiers in C must start with a letter or an underscore, followed by any combination of letters, digits, or underscores. They are case-sensitive and cannot be reserved keywords.

3. What is the difference between a keyword and an identifier?

Keywords are predefined words with special meanings in the C language. Identifiers, on the other hand, are user-defined names assigned to variables, functions, etc.

Leave a Reply

Your email address will not be published. Required fields are marked *