LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 8

Slot bookings with C23 constexpr and nullptr Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Using C23 constexpr for the size and nullptr for free slots, declare a table of bookings with designated initializers and list them.

Solution
main.c
#include <stdio.h>

int main(void) {
    constexpr int SLOTS = 4;
    static const char *bookings[SLOTS] = {[1] = "Asha", [3] = "Ravi"};   /* others are null */
    for (int i = 0; i < SLOTS; i++)
        printf("slot %d: %s\n", i, bookings[i] != nullptr ? bookings[i] : "free");
    return 0;
}

Output Verified by compiling and running

slot 0: free
slot 1: Asha
slot 2: free
slot 3: Ravi

The array size is a compile-time constant, so a static array is allowed. Unnamed elements of a pointer array are null pointers, and nullptr makes the comparison clearly a pointer test.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links