LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 16

A constexpr function used for an array size Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 16 Back to Exercise

What is the output of the following C++ program?

main.cpp
#include <iostream>

constexpr int cube(int x) { return x * x * x; }

int main() {
    int arr[cube(2)]{};
    static_assert(cube(3) == 27);
    int n = 4;
    std::cout << sizeof(arr) / sizeof(arr[0]) << ' ' << cube(n) << ' ' << arr[7] << '\n';
    return 0;
}
  • A 8 64 0 Correct
  • B 8 64 7
  • C 6 64 0
  • D Compilation error
Correct Answer: Option A

cube(2) is a constant expression, so it can size the array (8 elements, zero-initialized by {}). cube(n) with a run-time n simply runs at run time.

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