0

I want to make an array that holds a number of tile objects (called Tile) but it's saying that my constant int, numTiles, cannot be used as a... constant int... what? The code I'm having issues with is here (error on line 5):

// Variables - Tilemap
const int tileSize = 32;
const int screenWidth = GetScreenWidth();
const int numTiles = screenWidth / tileSize;
Tile tilemap[numTiles];

The error I get is as follows: expression must have a constant value the value of variable "numTiles" (declared at line 14) cannot be used a constant

I'm not sure why I'm getting this issue as it looks like numTiles is definitely a constant int... Can someone explain what the problem is here?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 3
    It needs to be a compile time constant. – Jim Nilsson Feb 24 '22 at 09:47
  • Can you explain what this means to me? I'm new to C++ and compiled programming languages as I've only ever worked with Python. – TheAngriestCrusader Feb 24 '22 at 09:49
  • 1
    The value `numTiles` can only be decided at runtime due to the call to `GetScreenWidth()`. The compiler has no idea of knowing what value `numTiles`will have so it can not statically allocate the array `tilemap`. You have to use dynamic memory allocation or use a suitable container which does e.g. `std::vector`. But I suggest you take an online course or similar in C++ if this concept is new to you. – Jim Nilsson Feb 24 '22 at 09:51
  • Change all those `const` by `constexpr`. (You should probably have error for `GetScreenWidth()`). – Jarod42 Feb 24 '22 at 09:53
  • Thank you for the thorough explanations from everyone, you were all very helpful and I understand how to fix my issue now. I'll definitely look more into runtime/compile time to prevent these issues in future. Thanks again! :) – TheAngriestCrusader Feb 24 '22 at 09:54

1 Answers1

2

Thanks to the people in the comments of the post for explaining this to me: The variables are calculated at runtime when they need to be calculated at compile time (this was due to my usage of GetScreenWidth(), which obviously cannot run during compilation).