Syed
Syed

Reputation: 65

Arrays declared globally gives out of scope error in functions

I have these arrays declared globally

char str1[] = "6541254939322816220209974565477289648317";
char str2[] = "3142522751761601737419090933147067701840";

int str1_size = strlen(str1);
int str2_size = strlen(str2);

int lcs[str1_size][str2_size];
int arrows[str1_size][str2_size];

But when I access this inside a function, it gives

lcs was not declared in this scope

also

array bound is not an integer constant before ‘]’ token
int lcs[str1_size][str2_size];

What am I doing wrong here ?

Upvotes: 1

Views: 33

Answers (1)

max66
max66

Reputation: 66200

First of all

int a[dim];

where dim isn't a compile-time know constant (constexpr by example) isn't C++ standard; maybe it's possible with some extension with some compiler but isn't C++ standard.

So, in your case

int lcs[str1_size][str2_size];
int arrows[str1_size][str2_size];

where str1_size and str2_size are normal (not constexpr, not const initialized with literals) variables, is an error.

If you could redefine str1_size and str2_size as follows

constexpt int str1_size = strlen(str1);
constexpr int str2_size = strlen(str2);

the lcs and arrows definition could works.

Unfortunately (1) str1 and str2 aren't constexpr and (2) std::strlen() isn't constexpr.

But if declare str1/str2 constexpr and write a constexpr alternative to std::strlen...

#include <iostream>

constexpr std::size_t lenStr (char const * str)
 {
   std::size_t  ret{};

   while ( *(str++) )
      ++ret;

   return ret;
 }

constexpr char str1[] = "6541254939322816220209974565477289648317";
constexpr char str2[] = "3142522751761601737419090933147067701840";

constexpr auto str1_size = lenStr(str1);
constexpr auto str2_size = lenStr(str2);

int lcs[str1_size][str2_size];
int arrows[str1_size][str2_size];

int main ()
 {
 }

Unfortunately the preceding code require C++14 (in C++11 it's impossible write so complex constexpr functions).

In C++11 you should write lenStr() in a recursive way

constexpr std::size_t lenStr (char const * str, std::size_t ret = 0u)
 { return *str ? lenStr(++str, ++ret) : ret; }

Upvotes: 1

Related Questions