Mastering C/C++: A Comprehensive Guide to Identifiers and Naming Conventions

Overview: This article primarily introduces the meaning of identifiers in C/C++ and their naming conventions. It aims to help readers quickly understand what variable names, function names, macro definitions, array names, etc., are, as well as their respective naming methods and rules.

1. Identifiers

In C language, identifiers mainly refer to variable names, array names, function names, and macro definitions.

2. Identifier Naming Rules

If an illegal identifier is used in the code, the compiler will prompt an error on the corresponding line during compilation/pre-compilation, and the compilation will fail.

  1. Character Range:

  • Can only contain: letters (A-Z, a-z), digits (0-9), and underscores (_).

  • Cannot contain special characters such as ?, #, *, &, @, ~ (e.g., *flag is an illegal name).

  • Case-sensitive (e.g., dog and Dog<span> are different identifiers).</span>

  • First Character:

    • Must start with a letter or an underscore, cannot start with a digit (e.g., 8data is an illegal name).

  • Length Limit:

    • The C language standard does not specify a length, but compilers usually have internal limits. For example, sometimes a single letter can represent a local variable within a function body, such as i, j, n often used for loop control variables. However, it is also not recommended to use overly long names; when naming, consider conciseness, readability, and common industry abbreviations. For example, count is often abbreviated as cnt, temp as tmp, and delete as del.

  • Keyword Conflicts:

    • Cannot have the same name as C language keywords (e.g., char, int, const, if, return, etc.). Generally, in an IDE or code editor, keywords will be displayed in different colors for distinction. Experts writing code in a text editor can distinguish which are reserved keywords in C language without color differentiation.

    3. Examples of Illegal Identifiers

    • 12345dog (starts with a digit, cannot start with a digit, can be changed to dog12345 or dog1)

    • my-name (contains a hyphen -, cannot use a hyphen, can be changed to my_name, using an underscore)

    • struct (conflicts with the keyword struct)

    • my name (contains a space, cannot use a space, can be changed to my_name or myName)

    4. Variable Definition

    data_type variable_name [= initial_value];// Square brackets indicate optional parts, meaning that an initial value can be assigned when declaring the variable name
    • Data Type: e.g., int (integer), unsigned int (unsigned integer), char (character), unsigned char (unsigned character), float (floating point), etc.

    • Variable Name: must comply with C identifier naming rules.

    • Initial Value (optional): can be directly assigned during definition, or can temporarily not have an initial value.

    • Examples:

    int a;   // declares an int variable a
    int a = 5;  // declares an int variable a and assigns an initial value of 5
    char name; // declares a char variable name
    char name = 'T'; // declares a char variable name and assigns an initial value of 'T'
    int 1test;  // illegal naming, cannot start with a digit
    int var value; // illegal naming, cannot have spaces
    int my_va#lue; // illegal naming, # character cannot be used for naming. Only letters (A-Z, a-z), digits (0-9), and underscores (_) are allowed
    5. Some Notes on Variables
    In C language, variables are declared before use. When declaring, it is not necessary to specify an initial value. Variables can be divided by scope into global variables and local variables. Global variables can be accessed in different functions of the code, even in different source code files, and their memory space coexists with the main program; while local variables, also known as temporary variables, are only valid within the function body, and when the function body reaches the end, they will automatically disappear, and the system will reclaim the memory space they occupied. From the above characteristics, we can see that when requesting variables, we should try to use local variables and reduce the use of global variables. This can reduce the system's memory overhead (especially in resource-limited embedded systems) and make the program code more readable. Many leading companies have specific requirements for variable naming styles to make the code clearer and more understandable during team maintenance, secondary development, and debugging.
    6. Notes on Function Names
    return_type function_name([parameter1_type parameter1, parameter2_type parameter2, ...]);
    • Return Type: can be int (integer, indicating that the function returns an integer value after execution), char (character, indicating that the function returns a character value after execution), void (no return value), etc.
    • Function Name: follows the same naming rules as variable names.
    • Function Parameters: also called formal parameters, mainly serve the purpose of passing parameters when calling the function. If the function has no formal parameters, the parameter part can be replaced with void (empty), and the number of formal parameters can be one or multiple.
    • Formal Parameter Role: serves as an interface for the function to receive external data.
    • Characteristics of Formal Parameters:

    1. Formal parameters are local variables of the function

    2. During the call, actual parameters assign values to formal parameters

    3. Changes to formal parameters do not affect actual parameters (unless using pointers)

    • Examples
    • The following example illustrates a function with a return value

    #include <stdio.h>

    // Returns the larger of two integers

    int max(int a, int b)

    {

    if (a > b)

    {

    return a;

    }

    else

    {

    return b;

    }

    }

    // Calculate square

    double square(double x)

    {

    return x * x;

    }

    // Return character type

    char get_first_letter(void)

    {

    return ‘A’;

    }

    int main()

    {

    int result = max(10, 20);// result = 20

    double sq = square(3.5);// sq = 12.25

    char letter = get_first_letter(); // letter = ‘A’

    printf(“Max: %d\n”, result);

    printf(“Square: %.2f\n”, sq);

    printf(“Letter: %c\n”, letter);

    return 0;

    }

    a. The following example illustrates a function with no return value

    #include <stdio.h>

    // No return value, only performs operations

    void print_hello(void)

    {

    printf(“Hello, World!\n”);

    // No need for a return statement, or can use return;

    }

    // Print custom message

    void print_message(char* msg)

    {

    printf(“Message: %s\n”, msg);

    }

    int main()

    {

    print_hello(); // Direct call, does not receive return value

    print_message(“This is a test”);

    return 0;

    }

    b. The following example illustrates basic usage of formal parameters (advanced usage of formal parameters such as arrays, pointers, etc., will be introduced in a separate article later)

    #include <stdio.h>

    // Two integer formal parameters

    int add(int a, int b)

    {

    return a + b;

    }

    // Multiple different types of formal parameters

    void print_info(char* name, int age, double height)

    {

    printf(“Name: %s, Age: %d, Height: %.2f\n”, name, age, height);

    }

    // No-parameter function

    int get_fixed_number(void)

    {

    return 42;

    }

    int main()

    {

    int sum = add(5, 3);// 5 and 3 are actual parameters

    print_info(“Tom”, 25, 1.68);

    int num = get_fixed_number();

    printf(“Sum: %d\n”, sum);

    printf(“Fixed number: %d\n”, num);

    return 0;

    }

    7. Notes on Macro Definitions

    Macro definitions are used for text replacement in the source code before compilation, simply put, they give it an easier-to-understand and read alias, and the compiler first performs text replacement before compiling. All letters in macro definitions are written in uppercase.

    The following examples illustrate:

    #define PI 3.14159

    #define MAX_SIZE 100

    #define AUTHOR “Tom”

    int main()

    {

    float area = PI * 2 * 2; // Before compilation: float area = 3.14159 * 2 * 2;

    char buffer[MAX_SIZE]; // Before compilation: char buffer[100];

    printf(“By %s”, AUTHOR); // Before compilation: printf(“By %s”, “Alice”);

    return 0;

    }

    The C standard defines some predefined macros that are very useful, especially in debugging and logging.

    Macro Meaning
    <span>__FILE__</span> String literal of the current source code file
    <span>__LINE__</span> Integer literal of the current code line
    <span>__DATE__</span> Compilation date, string in the format “Mmm dd yyyy”
    <span>__TIME__</span> Compilation time, string in the format “hh:mm:ss”
    <span>__func__</span> (C99) Function name of the current function (non-standard macro, but widely supported)
    <span>__STDC__</span> If the compiler follows the ANSI C standard, the value is 1
    Example:
    printf("Compiled on %s at %s",__DATE__,__TIME__);// Print compilation date and time
    printf("Error in file %s at line %d",__FILE__,__LINE__);// Print the name of the file where the error occurred, and the line number

    7. Notes on Arrays

    • General expression of arrays

      data_type array_name[array_size];

    The naming rules for array names follow the naming rules for identifiers.

    The following examples illustrate:

    int arr1[5];// Declare an array containing 5 integers (uninitialized)

    int arr2[5] = {1, 2, 3, 4, 5};// Declare and fully initialize

    int arr3[5] = {1, 2, 3}; // Partially initialized, unspecified will be randomly generated

    int arr4[] = {1, 2, 3, 4, 5}; // Compiler infers size as 5

    // Character array (string)

    char str1[] = “Hello”; // Automatically includes ‘\0’, size is 6

    • Accessing Arrays

    array_name[index] // Access or modify elements

    The following examples illustrate:

    int main()

    {

    int numbers[5] = {10, 20, 30, 40, 50};

    // Access elements

    printf(“First element: %d\n”, numbers[0]); // 10

    printf(“Third element: %d\n”, numbers[2]); // 30

    // Modify elements

    numbers[1] = 25; // Modify the second element

    printf(“Modified second element: %d\n”, numbers[1]); // 25

    // Traverse the array

    printf(“All elements in the array: “);

    for (int i = 0; i < 5; i++)

    {

    printf(“%d “, numbers[i]);

    }

    printf(“\n”);

    // Calculate array length (important technique!)

    int size = sizeof(numbers) / sizeof(numbers[0]);

    printf(“Array length: %d\n”, size);

    return 0;

    }

    Original content is not easy to create, please like, follow, and bookmark! Thank you!

    Leave a Comment