2

I have a c++ program where I need to pass the square root of a number in a for loop.


#include<random>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
#include <omp.h>

using namespace std;
int main()
{
vector<int>inputDataBits(49);                                    // vector of randomly generated input data bits
#ifdef printDebug
    std::cout << "the input data bits are" << endl;
    std::cout << "-------------------------" << endl << endl;
    int var =49;
    const int r=(int)sqrt(var);
    float input2d[r][r];
    for (int i = 0; i < r; i++)
    {
        for (int j = 0; j < r; j++)
        {
            input2d[i][j] = inputDataBits[(j %r) + (i *r)];
            std::cout << input2d[i][j] << "\t";
        }
        std::cout << endl << endl;
    }
    std::cout << endl << endl;
#endif
return 0;
}

I get an error 'expression must have a constant value'. Is there a way to do this in c++?

Divs
  • 19
  • 3
  • Does changing var to `const int var` help? – Dario Petrillo Mar 29 '21 at 06:53
  • VLAs (like in `float input2d[r][r]`) are non standard in C++. The Microsoft compiler (I suppose that's the one you use) does not support them. – Jabberwocky Mar 29 '21 at 06:57
  • Note that there's difference between const and constexpr. https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const – Omid Mar 29 '21 at 07:00

2 Answers2

3

This is the purpose of the constexpr keyword (make the value known at compile time).

  constexpr int var=49;
  constexpr int r=(int)sqrt(var);

Unfortunately, in the documentation sqrt() is not declared as a constexpr function. Only gcc seems to consider it as constexpr but it is not portable.

prog-fh
  • 13,492
  • 1
  • 15
  • 30
0

The size of an array needs to be known at compile-time.

Instead you can use a std::vector, which has a dynamic size.

std::vector<std::vector<float>> input2d(std::vector<float>(r), r);
super
  • 12,335
  • 2
  • 19
  • 29