0

I read that the size of array should be known at compile time.

If I am right then below code should not work, but it is compiling without any warnings and is working fine.

Could you please explain me what is happening ?

std::string s = "ABCDEFGHIJ"; 

 int n = s.length(); 

// declaring character array 
char char_array[n + 1];

std::cout << sizeof(char_array) << std::endl;

//Actual result

11

1 Answer 1

4

Assuming you're using g++, it's a nonstandard compiler extension. The keyword to search for is "variable length array".

Since you didn't explain what compiler you're using, I'll show an example of how to enable errors for this kind of code with g++ using either the -pedantic flag or explicitly enabling vla warnings / errors.

demo:/tmp$ cat ex.cc

#include <iostream>
#include <string>

int main() {
  std::string s = "ABCDEFGHIJ";
  char char_array[s.length() + 1];
  std::cout << sizeof(char_array) << std::endl;
}

demo:/tmp$ cat ex.cc | g++ -x c++ -

demo:/tmp$ cat ex.cc | g++ -Werror=vla -x c++ -
<stdin>: In function ‘int main()’:
<stdin>:6:33: error: variable length array ‘char_array’ is used [-Werror=vla]
cc1plus: some warnings being treated as errors

demo:/tmp$ cat ex.cc | g++ -pedantic -x c++ -
<stdin>: In function ‘int main()’:
<stdin>:6:33: warning: ISO C++ forbids variable length array ‘char_array’ [-Wvla]

demo:/tmp$ g++ --version | head -n 1
g++ (Debian 8.3.0-6) 8.3.0
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.