WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C · Basic · question 5 of 100

What is a constant, and how do you define one in C?

📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

In C programming language, a constant is a value that cannot be modified during program execution. Constants are useful when you need to define a value that is used throughout your program and should not be changed. Here’s how you can define a constant in C:

Using the #define preprocessor directive: The #define preprocessor directive is used to define a constant value at the beginning of a program. The syntax for using #define is:

    #define PI 3.14159265359

In this example, the constant PI is defined as 3.14159265359. Once defined, the value of PI cannot be changed during program execution.

Using the const keyword: The const keyword is used to define a variable that cannot be modified during program execution. The syntax for using const is:

    const int MAX_VALUE = 100;

In this example, the constant MAX_VALUE is defined as 100 using the const keyword. The value of MAX_VALUE cannot be modified during program execution.

Here is an example of how constants can be used in a C program:

    #include <stdio.h>
    
    #define PI 3.14159265359
    const int MAX_VALUE = 100;
    
    int main() {
        float radius = 5.0;
        float circumference = 2 * PI * radius;
        printf("Circumference: %fn", circumference);
        
        // MAX_VALUE = 200; // This will result in an error
        printf("Max value: %dn", MAX_VALUE);
        return 0;
    }

In this example, the constant PI is defined using the #define directive, while the constant MAX_VALUE is defined using the const keyword. Both constants are used to perform calculations in the main() function. Attempting to modify the value of MAX_VALUE will result in an error, demonstrating the immutability of constants in C.

Using constants can make your code more readable, maintainable, and less error-prone. Constants are useful when you need to define values that should not be changed during program execution, and using them can help prevent accidental modifications that could lead to bugs or unexpected behavior.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview — then scores it.
📞 Practice C — free 15 min
📕 Buy this interview preparation book: 100 C questions & answers — PDF + EPUB for $5

All 100 C questions · All topics