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

C · Advanced · question 47 of 100

How do you use the "const" keyword with pointers in C?

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

In C, the const keyword is used to specify that a variable’s value cannot be changed once it has been initialized. When used with pointers, it can specify that the value pointed to by the pointer is constant and cannot be modified.

There are two ways to use the const keyword with pointers in C. The first is to specify that the pointer itself is constant, and cannot be used to modify the value it points to. The second is to specify that the value pointed to by the pointer is constant, and cannot be modified through the pointer.

Here are examples of both uses of the const keyword with pointers:

    // const pointer to int
    int num = 5;
    const int *ptr1 = #
    // *ptr1 = 6; // error: assignment of read-only location
    num = 6; // okay: num is not const
    
    // pointer to const int
    const int num2 = 7;
    int *const ptr2 = (int*)&num2; // cast away const for demonstration purposes
    // *ptr2 = 8; // error: assignment of read-only location
    // ptr2 = # // error: assignment of read-only variable

In the first example, we declare a variable num of type int and initialize it to 5. We then declare a pointer ptr1 to a constant integer using the const keyword. This means that the value pointed to by ptr1 cannot be changed through the pointer. We demonstrate this by attempting to assign a new value to *ptr1, which results in a compile-time error. However, we can still modify num directly.

In the second example, we declare a constant integer num2 and initialize it to 7. We then declare a pointer ptr2 to a non-constant integer using the const keyword after the *. This means that ptr2 cannot be used to modify the value pointed to by the pointer, but we can still modify the value directly by casting away the const. We demonstrate this by attempting to assign a new value to *ptr2, which results in a compile-time error. However, we can still modify num2 directly.

In general, using the const keyword with pointers can help prevent unintended modifications to values, which can improve the safety and reliability of C programs.

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