Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There is such code:

#include <iostream>

int main()
{
  int size;
  std::cin >> size;

  size = size + 1;
  int tab3[size];

  tab3[0] = 5;
  std::cout << tab3[0] << " " << sizeof(tab3) << std::endl;
  return 0;
}

The result is:

$ g++ prog.cpp -o prog -Wall -W 
$ ./prog
5
5 24

Why does this code even compile? Shouldn't be length of array a constant variable?

I used g++ version 4.4.5.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

Variable-length arrays in C++ are available as an extension in GCC. Compiling with all warnings should have alerted you to that fact (include -pedantic).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...