Identifiers in C

Identifiers are names for variables, functions, arrays, and other parts of a C program. They help make the code clear and easy to understand. This article explains what identifiers are, how to name them, and why they are important. It also shows common mistakes and how to avoid them. With simple explanations and useful examples, you will learn to use identifiers correctly in C programming.

Contents:

  1. What are Identifiers in C?
  2. Rules for Naming Identifiers in C
  3. Examples of Identifiers in C
  4. Differences Between Identifiers and Keywords in C
  5. Types of Identifiers in C
  6. Scope of Identifiers in C
  7. Lifetime of Identifiers in C
  8. Best Practices for Naming Identifiers in C
  9. FAQs on Identifiers in C

What are Identifiers in C?

An identifier in C is the name used to identify variables, functions, arrays, or other user-defined entities. It is a symbolic name assigned to program elements to refer to them in the code.

Syntax:

<datatype> identifier_name;

advertisement

Rules for Naming Identifiers in C

  • Must begin with a letter (A-Z or a-z) or an underscore (_).
  • Can be followed by letters, digits (0-9), or underscores.
  • Cannot be a C keyword (e.g., int, return, etc.).
  • Case-sensitive (e.g., score and Score are different).
  • Avoid very short names unless used in loops (e.g., i, j, k).
  • No special characters allowed except the underscore (_).
  • No spaces allowed (myVariable is valid, but my Variable is not).
  • Use meaningful names for clarity, such as totalMarks instead of tm.
  • Maintain a consistent naming convention, such as camelCase (totalMarks) or snake_case (total_marks).

Examples of Identifiers in C

Valid Identifiers Examples:

int sanfoundryScore;    // Variable to store score
float averageMarks;     // Variable for marks
char studentName[50];   // Array to store student name
void displayResult();   // Function to display result

Invalid Identifiers Examples:

Free 30-Day Java Certification Bootcamp is Live. Join Now!
int 123marks;         // Cannot start with a digit
float avg-score;      // Hyphens not allowed
char return;          // Cannot use keywords

Example 1:

#include <stdio.h>
 
int main()
{
    int quizScore = 90;          // Valid identifier
    float sanfoundryPercentage = 95.5; 
 
    printf("Quiz Score: %d\n", quizScore);
    printf("Sanfoundry Percentage: %.2f\n", sanfoundryPercentage);
 
    return 0;
}

Output:

Quiz Score: 90
Sanfoundry Percentage: 95.50

The program creates two variables: quizScore (a whole number) and sanfoundryPercentage (a decimal number). It then shows their values on the screen using printf(). The %d prints the whole number, and %.2f prints the decimal with two places. The program finishes with return 0;, meaning it ran successfully.

Example 2:

#include <stdio.h>
 
// Function to calculate internship stipend
int calculateStipend(int codingHours, int quizScore)
{
    int stipend = (codingHours * 50) + (quizScore * 20);
    return stipend;
}
 
int main() {
    int codingHours = 30;    // Valid identifier
    int quizScore = 90;      // Valid identifier
 
    int totalStipend = calculateStipend(codingHours, quizScore);
 
    printf("Coding Hours: %d\n", codingHours);
    printf("Quiz Score: %d\n", quizScore);
    printf("Total Stipend: %d\n", totalStipend);
 
    return 0;
}

Output:

Coding Hours: 30
Quiz Score: 90
Total Stipend: 3300

The program calculates an internship stipend based on coding hours and quiz scores. The calculateStipend() function multiplies codingHours by 50 and quizScore by 20, then adds both values. In main(), codingHours is set to 30 and quizScore to 90. The function returns the total stipend, which is displayed using printf(). The program ends with return 0;, meaning it ran successfully.

advertisement

Differences Between Identifiers and Keywords in C

Here is the comparison table between identifiers and keywords in C are:

Feature Identifiers Keywords
Definition Identifiers are names assigned to variables, functions, arrays, etc. Keywords are predefined reserved words in C with special meanings.
Purpose Used to uniquely name program elements. Used to define the syntax and structure of the C language.
User-defined? Yes, programmers define identifiers. No, keywords are predefined by the C language.
Can be modified? Yes, programmers can change them. No, their meanings stay fixed.
Examples age, totalMarks, sum int, float, while, return
Case Sensitivity Case-sensitive (Sum and sum are different). Also case-sensitive (Int is not the same as int).
Rules for Naming Can contain letters, digits, and underscores (_). Cannot start with a digit. Cannot be a keyword. Fixed by the language. Cannot be used as an identifier.
Total Count Unlimited (depends on the program’s needs). Limited (C has a fixed number of keywords, e.g., 32 in C89).
Usage in Program Can be used to define variables, functions, arrays, etc. Used to define program structure and control flow.

Types of Identifiers in C

In C, identifiers refer to the names assigned to various program elements like variables, functions, arrays, and structures. Identifiers can be classified based on their scope, lifetime, and purpose.

  1. Variables: Store data values of a specific type.
  2. int marks;       // Integer variable
    float percentage; // Floating-point variable
  3. Functions: Perform tasks and can be user-defined or built-in.
  4. void displayResult() {
        printf("Sanfoundry Results Published\n");
    }
  5. Arrays: Hold multiple values of the same data type.
  6. int sanfoundryScores[5] = {90, 85, 88, 92, 95};
  7. Structures: Group different data types under one name.
  8. struct SanfoundryStudent {
        char name[50];
        int id;
        float score;
    };
  9. Pointers: Store memory addresses of variables.
  10. int marks = 100;
    int *ptr = &marks;
  11. Constants: Hold fixed values that do not change.
  12. #define MAX_MARKS 100
    const float PI = 3.14;
  13. Macros: Define reusable code snippets or constants.
  14. #define SANFOUNDRY 1
  15. Labels: Control program flow using goto.
  16. goto label;
    label:
        printf("Welcome to Sanfoundry Quiz!\n");

Scope of Identifiers in C

The scope of an identifier determines where it can be accessed or modified in the program. There are four types:

1. Local Scope
Variables declared inside a function or block are only accessible within that function or block.

Example:

#include <stdio.h>
 
void sanfoundryQuiz() {
    int score = 90;  // Local variable
    printf("Sanfoundry Score: %d\n", score);
}
 
int main() {
    sanfoundryQuiz();
    // printf("%d", score);  // Error: score is not accessible here
    return 0;
}

Output:

Sanfoundry Score: 90

2. Global Scope

Variables declared outside any function or block are accessible throughout the program.

Example:

#include <stdio.h>
 
int totalParticipants = 100;  // Global variable
 
void sanfoundryResults() {
    printf("Total Participants: %d\n", totalParticipants);
}
 
int main() {
    sanfoundryResults();
    printf("Participants confirmed: %d\n", totalParticipants);
    return 0;
}

Output:

Total Participants: 100
Participants confirmed: 100

3. Function Scope

Variables declared inside a function are only accessible within that function.

Example:

#include <stdio.h>
 
void sanfoundryPractice(int attempts) {
    int maxAttempts = 3;  // Function scope
    if (attempts < maxAttempts) {
        printf("Try Again!\n");
    } else {
        printf("Max Attempts Reached\n");
    }
}

Output:

Try Again!
Max Attempts Reached

4. File Scope

Variables declared with static outside any function retain their value between function calls but are accessible only within the same file.

Example:

#include <stdio.h>
 
static int sanfoundryID = 101;  // File scope
 
void displayID() {
    printf("Sanfoundry ID: %d\n", sanfoundryID);
}

Output:

Sanfoundry ID: 101

Lifetime of Identifiers in C

The lifetime of an identifier defines how long a variable remains in memory during program execution. There are three types:

1. Automatic (auto) Variables
Variables declared inside a block with auto (default) are automatically destroyed when the block is exited.

Example:

#include <stdio.h>
 
void sanfoundrySession()
{
    auto int session = 1;
    printf("Sanfoundry Session %d\n", session);
}

Output:

Sanfoundry Session 1

The program has a function called sanfoundrySession(). Inside, it creates a number variable session and sets it to 1. The printf() function shows “Sanfoundry Session 1” on the screen. The auto keyword is used, but it is not needed because local variables are automatic.

2. Static Variables

Variables declared with static retain their value between multiple function calls.

Example:

#include <stdio.h>
 
void sanfoundryCounter() {
    static int count = 0;  // Static variable
    count++;
    printf("Attempt %d\n", count);
}
 
int main() {
    sanfoundryCounter();
    sanfoundryCounter();
    sanfoundryCounter();
    return 0;
}

Output:

Attempt 1
Attempt 2
Attempt 3

The program has a function called sanfoundryCounter(). Inside, it creates a static number count and sets it to 0. Each time the function runs, count increases by 1. The printf() function shows “Attempt 1”, “Attempt 2”, and “Attempt 3” on the screen. The static keyword keeps the value even after the function ends.

3. Dynamic Variables

Memory allocated using malloc() or calloc() remains in memory until explicitly freed using free().

Example:

#include <stdio.h>
#include <stdlib.h>
 
int main() {
    int *score = (int *)malloc(sizeof(int));
    *score = 95;
    printf("Sanfoundry Quiz Score: %d\n", *score);
    free(score);
    return 0;
}

Output:

Sanfoundry Quiz Score: 95

The program creates a number variable score using dynamic memory allocation with malloc(). It assigns 95 to score and prints “Sanfoundry Quiz Score: 95” on the screen. The free() function releases the memory after use. This helps manage memory efficiently.

Best Practices for Naming Identifiers in C

  1. Use Meaningful Names: Choose names that describe the purpose of the variable, function, or constant.
  2. int studentCount;  // Good
    int sc;            // Avoid
  3. Follow Naming Conventions: Use camelCase for variables and functions and use PascalCase for structures and constants.
  4. int totalMarks;         // Variable
    float calculateGrade(); // Function
  5. Avoid Single Character Names (Unless Loop Variables): Use single characters like i, j, and k only for loop counters or temporary variables.
  6. for (int i = 0; i < 10; i++) {
        printf("%d\n", i);
    }
  7. Start with a Letter or Underscore: Identifiers should begin with a letter (A-Z, a-z) or an underscore (_).
  8. int _tempValue;   // Valid
    int 1value;       // Invalid
  9. Avoid Reserved Keywords: Do not use C language reserved keywords as identifiers.
  10. int int;  // Invalid
  11. Be Consistent with Case: C is case-sensitive, so be consistent with uppercase and lowercase letters.
  12. int sanfoundryQuiz;  // Valid
    int SanfoundryQuiz;  // Different identifier
  13. Use Constants for Fixed Values: Use #define or const to define constant values.
  14. #define MAX_SCORE 100
    const float PI = 3.14;

FAQs on Identifiers in C

1. What is an identifier in C?
An identifier is the name of a variable, function, array, or other user-defined item. It helps to identify them in a program.

2. Can an identifier start with a number?
No, it cannot start with a number. For example, 1variable is wrong, but variable1 is correct.

3. Are identifiers case-sensitive in C?
Yes, they are. For example, Age and age are different names in C.

4. Can we use special characters in identifiers?
No, you cannot use **@, $, %, or *** in identifiers. Only letters, numbers, and underscores are allowed.

5. How long can an identifier be in C?
Most compilers allow up to 31 characters for uniqueness, but longer names help readability.

6. Can we use underscores in identifiers?
Yes, underscores are allowed. They are often used to separate words, like max_value.

7. Why should we follow naming conventions?
Good names make code easier to read and understand. For example, totalSalary is better than x.

Key Points to Remember

Here is the list of key points we need to remember about “Identifiers in C”.

  • Identifiers are names for variables, functions, and other parts of a C program to make the code easy to understand.
  • An identifier must start with a letter (A-Z or a-z) or an underscore (_) and can only have letters, numbers, and underscores.
  • Identifiers are created by programmers, but keywords are special words in C that have fixed meanings and cannot be used as names.
  • Identifiers include variables, functions, arrays, and structures, each used for different tasks in a program.
  • The lifetime of an identifier depends on how it is created—some exist only for a short time, while others stay in memory longer.
  • Identifiers have different scopes, meaning they can be used in a small part of the program or throughout the whole program.
  • Common mistakes include using spaces, starting with a number, using special symbols, or choosing a keyword as a name.
  • Good practices include using clear and meaningful names, following naming rules, avoiding keywords, and keeping names consistent.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.