3

For this same program c++11 return 2 1 2, but for c++14 return 2 1 1 to me. I am confused..

#include <iostream>
#include <string>
using namespace std;
int main()
{
    char a[2];
   cout << sizeof(a) << endl; 

   std::string b("a");
   cout << b.size() << endl;


   char c[b.size() + 1];
   cout << sizeof(c) << endl;

   return 0;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Bryan Fok
  • 3,277
  • 2
  • 31
  • 59
  • What version of the compiler are you using? The only version I found that prints "2 1 1" also gives a warning with -Wall: "warning: taking sizeof array of runtime bound". That might date from the time the committee tried to standardize VLA. – Marc Glisse Aug 21 '17 at 05:34
  • 1
    Variable length arrays are part of the C standard, but not C++. https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – edA-qa mort-ora-y Aug 21 '17 at 06:38

3 Answers3

15

char c[b.size() + 1]; is not allowed in Standard C++, any version.

If you find a compiler accepts this then it is a compiler extension, so you should consult the documentation for whichever compiler you used.

M.M
  • 138,810
  • 21
  • 208
  • 365
9

The following line is not standard C++.

char c[b.size() + 1];

It is supported by some compilers as an extension. They are not expected to confirm to any standard. They may return whatever makes sense from their implementation point of view when they evaulate sizeof(c).

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

In addition to the answers, I would like to add that this term is known as Variable Length Array and it is an extension in C++ since C99. VisualC++ compiler always outputs this as an error, however GCC and Clang does not.

Only if you add -pedantic flag to your flags it will output warning: ISO C++ forbids variable length array 'c' [-Wvla]

Hakes
  • 631
  • 3
  • 13