LearnFrenzy
Sign in Take a free test

C Const · const Programs · Question 8

Identity matrix with C23 constexpr sizes Solution, output & explanation

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

Using C23 constexpr for the size, build and print a 4 × 4 identity matrix in a file-scope array.

Solution
main.c
#include <stdio.h>

constexpr int N = 4;
static int identity[N][N];          /* allowed: N is a constant expression */

int main(void) {
    for (int i = 0; i < N; i++)
        identity[i][i] = 1;
    for (int r = 0; r < N; r++) {
        for (int c = 0; c < N; c++)
            printf("%d ", identity[r][c]);
        printf("\n");
    }
    return 0;
}

Output Verified by compiling and running

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

A file-scope array needs a constant size. Before C23 that meant #define N 4 or an enum; constexpr int N = 4; gives the same compile-time constant with a real type and scope. The static array starts zeroed, so only the diagonal is set.

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