Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Rules to Name an Identifier in C
2.1.
Start with a Letter or an Underscore
2.2.
Keep It Unique in the Scope
2.3.
Avoid Reserved Keywords
2.4.
Length Matters
3.
Examples of Identifiers in C
3.1.
Variables
3.2.
Functions
3.3.
Arrays
3.4.
C
4.
What Happens if We Use a Keyword as an Identifier in C?
4.1.
Compiler Confusion
4.2.
Error Messages
4.3.
Code Won't Compile
5.
Frequently Asked Questions
5.1.
What if I accidentally use a C keyword as an identifier?
5.2.
Can identifiers contain special characters like @, $, or %?
5.3.
Is it okay to start an identifier with an underscore?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Identifiers in C

Author Rinki Deka
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Identifiers in C play a crucial role in the programming world, serving as the names you give to various elements such as variables, functions, arrays, and so on. These names help us reference specific pieces of data throughout our code, making it readable and maintainable. 

Identifiers in C

In this article, we'll explore the conventions and rules for naming identifiers in C, look at practical examples, and discuss what happens when identifiers clash with keywords. By the end of this article, you'll have a solid understanding of how to effectively name and use identifiers in your C programming projects.

Rules to Name an Identifier in C

When you're programming in C, naming your identifiers—like variables, functions, and arrays—is not just about slapping on any name you like. There's a method to the madness, ensuring your code is clean, understandable, and error-free. Here's the lowdown on how to name your identifiers right:

Start with a Letter or an Underscore

Your identifier names should kick off with either a letter (a-z, A-Z) or an underscore (_). For example, total, _count, or userName are all good to go.

Numbers Are Cool, But Not at the Start: Feel free to sprinkle in numbers (0-9) in your identifier names, but not at the beginning. var1 works, but 1var doesn't cut it.

Keep It Unique in the Scope

Identifiers need to be one-of-a-kind within their scope. So, if you've already used total in a function, don't use it again for something else in the same function.

Avoid Reserved Keywords

C has reserved keywords like int, return, and for. These are off-limits as identifier names because they have special meanings in C.

Length Matters

In C, identifiers can be pretty long (up to 31 characters for some compilers), but keeping them concise and meaningful is key. Long names can make your code hard to read and maintain.

Remember, the goal is to make your code as clear and readable as possible. Good identifier names can tell you a lot about what a piece of code does without having to dive deep into the logic.

// Good examples

int itemCount;
double totalPrice;
char userName[50];


// Not-so-good examples

int 1stNumber;  // Starts with a number
double double;  // Uses a reserved keyword
char user-name[50];  // Contains a hyphen
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples of Identifiers in C

To get a better grip on how to use identifiers in C, let's walk through some examples. These will show you how identifiers can be used for various elements like variables, functions, and arrays, making your code not just functional but also easy to read and understand.

Variables

In C, variables are like containers in your fridge, each holding a specific type of food (or data). For instance, if you're keeping track of scores in a game, you might use an integer variable named score.

int score = 95;

Functions

Functions in C are like recipes. Each recipe (function) has a name, and when you want to whip up that dish (run the function), you call it by its name. For example, a function to add two numbers might be named addNumbers.

int addNumbers(int num1, int num2) {
    return num1 + num2;
}

Arrays

Think of arrays as egg cartons. Each section of the carton holds one egg, just like each element of an array holds one piece of data. If you have a list of scores, you might use an array named scores.

int scores[5] = {90, 85, 88, 92, 95};

When choosing names for your identifiers, make sure they give a clear idea of what they're used for. A variable named x doesn't say much, but userAge tells you exactly what it stores.

Let's combine what we've learned about identifiers in C into a single example. In this code snippet, we'll use variables, functions, and an array, all with clear and meaningful names, to calculate and display the average score from a list of scores.

  • C

C

#include <stdio.h>

// Function to calculate the average score

double calculateAverage(int scores[], int size) {

   int sum = 0;

   for (int i = 0; i < size; i++) {

       sum += scores[i]; // Add each score to the sum

   }

   return (double)sum / size; // Calculate & return the average

}

int main() {

   // Array of scores

   int scores[5] = {85, 90, 75, 100, 95};

   int numOfScores = 5; // Total number of scores

 // Variable to hold the average score, using the 'calculateAverage' function

   double averageScore = calculateAverage(scores, numOfScores);

// Print the average score

   printf("The average score is: %.2f\n", averageScore);

 return 0;

}

Output

The average score is: 89.00

In this example:

  • scores is an array identifier that holds the scores we want to average.
     
  • numOfScores is a variable identifier that stores the total number of scores in the array.
     
  • calculateAverage is a function identifier that takes an array of scores and its size to calculate the average.
     
  • averageScore is a variable identifier used to store the result returned by the calculateAverage function.

What Happens if We Use a Keyword as an Identifier in C?

In C programming, keywords are special words that are reserved for specific purposes. These words, like int, return, and for, are the building blocks of C syntax and are used to perform various operations in the language. But what happens if you accidentally (or intentionally) use one of these keywords as an identifier for your variables or functions? Let's break it down:

Compiler Confusion

The compiler, which is the tool that turns your C code into a program the computer can run, gets confused. It's like calling two different students in class by the same name; when you call out to them, they both might respond, creating confusion.

Error Messages

When you use a keyword as an identifier, the compiler will most likely throw an error message. It's the compiler's way of saying, "Hey, I don't understand what you're trying to do here." The error message might not always be clear, but it's basically the compiler asking for clarification.

Code Won't Compile

The bottom line is, your code won't compile. This means you won't be able to run it until you fix the issue by renaming the identifier to something that isn't a keyword.

Here's an example to illustrate the point:

int int = 5; // Attempting to use 'int' as a variable name


In this case, int is a keyword used to declare integer type variables. Using it as a variable name causes an error. The compiler will stop with a message along the lines of "syntax error" or "expected identifier," depending on the compiler you are using.

To avoid these issues, always ensure that your identifiers are unique and do not clash with C's reserved keywords. A good practice is to choose meaningful names that clearly describe what the variable or function does, avoiding the use of keywords altogether.

Frequently Asked Questions

What if I accidentally use a C keyword as an identifier?

Using a keyword as an identifier will confuse the C compiler, leading to errors. The compiler expects keywords to play specific roles in your code, so it won't understand your intention if you use one as a name for a variable or function.

Can identifiers contain special characters like @, $, or %?

No, identifiers in C can only include letters, digits, and underscores. Special characters are not allowed because they either serve other purposes in C or could lead to ambiguity and errors in your code.

Is it okay to start an identifier with an underscore?

Yes, but with caution. Identifiers beginning with an underscore are typically reserved for system libraries and could conflict with names in future versions of C or with other libraries. It's generally safer to start with a letter to avoid such conflicts.

Conclusion

Identifiers in C are the foundational blocks of readable and maintainable code, acting as the labels for variables, functions, and more. By adhering to the naming rules and understanding the potential pitfalls, like clashing with keywords, you ensure your code is clear and error-free. Remember, the key is to use names that are descriptive and meaningful, which not only makes your code easier to follow but also eases collaboration and future modifications. With the insights and examples provided, you're now equipped to use identifiers effectively in your C programming endeavors, laying the groundwork for robust and efficient code.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass