Cant we use static cast on double for std::array size? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Cant we use static cast on double for std::array size?

Hi I am aware that std::array is compile time and it must need to know size of array in compilation stage. Also let me know if i am wrong but static cast to long int is also compile time operation. Isnt it ? (Only dynamic cast is run time operstion in four basic castings) If so, why still a5 is not inialized and results compile time error ? https://code.sololearn.com/c441XfmZlAtQ/?ref=app

21st Sep 2023, 6:20 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
3 Answers
+ 1
a1 is valid because you're using a constant expression (literal values) to define its size. a2 will not work because x is not const, and the size of std::array must be a compile-time constant. a3 is valid because y is const, which means it's known at compile time and can be used as the size of the array. a4 is valid because z is declared as constexpr, which also means it's known at compile time and can be used as the size of the array. a5 is using a static_cast with dy, which is a double. The static_cast will convert it to a long unsigned int, but this cast happens at runtime, not at compile time. So, this code will not work as the size must be known at compile time, and casting a runtime value won't achieve that https://code.sololearn.com/cZ0V7U68vINi/?ref=app
21st Sep 2023, 7:22 PM
Knight
Knight - avatar
+ 1
I had different opinion of static cast. It is compile time operation. But you named it as run time. Refer below: https://stackoverflow.com/questions/27309604/do-constant-and-reinterpret-cast-happen-at-compile-time Static cast is compile time only.
22nd Sep 2023, 4:04 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Hi, you are right about 'static_cast' is a compile-time operation, it's important to understand the context in which it's being used. in a5 declaration line, you're trying to use a non-constant value (dy, which is of type 'const double') as the size of the array. Even though the 'static_cast' is a compile-time operation, the value being casted (dy) is not know at compile time because it's based on a variable (const double dy) that can be determined only at runtime. Therefore, this usage is not allowed for determining the size of an std::array. If you want to specify the size of the array at compile time, you must use a constant expression, like you did with constexpr int z = 3; where 'z' is know at compile time.
22nd Sep 2023, 3:04 PM
Amine Laaboudi
Amine Laaboudi - avatar