5
#include <iostream>
#include <math.h>

using namespace std;

int main() {
    int    i{100};
    float  f{3.14};
    double d{3.14159};
    cout<<"size of int is: "   <<sizeof(i)<<endl;
    cout<<"size of float is: " <<sizeof(f)<<endl;
    cout<<"size of double is: "<<sizeof(d)<<endl<<endl;;

    auto x = sin(3.14159);
    cout<<"size of auto that is double is: "<<sizeof(x)<<endl<<endl;

    auto y{sin(3.14159)};
    cout<<"size of auto that is double is: "<<sizeof(y)<<endl;
    return 0;
}

The output is:

size of int is: 4

size of float is: 4

size of double is: 8

size of auto that is double is: 8

size of auto that is double is: 16

Why is sizeof(y) 16?

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 9
    That's a defect in C++11, `y` is an `initializer_list`. – dyp Aug 15 '15 at 15:28
  • See also: http://stackoverflow.com/q/31301369/ and http://stackoverflow.com/q/25612262/ – dyp Aug 15 '15 at 15:47
  • 3
    The defect has been fixed by http://open-std.org/JTC1/SC22/WG21/docs/papers/2014/n3922.html, and gcc 5 and msvc 2015 ship the fix. y is double, and gcc 5 reports 8 for its size. – Ville Voutilainen Aug 15 '15 at 16:14
  • Dup? http://stackoverflow.com/questions/25612262/why-does-auto-x3-deduce-an-initializer-list?rq=1 – curiousguy Aug 17 '15 at 02:02

1 Answers1

6

Using "typeid" with gcc 4.8.4 as follows:

#include <iostream>
#include <math.h>
#include <typeinfo>

using namespace std;

int main() {
    int    i{100};
    float  f{3.14};
    double d{3.14159};
    cout<<"size of int is: "   <<sizeof(i)<<endl;
    cout<<"size of float is: " <<sizeof(f)<<endl;
    cout<<"size of double is: "<<sizeof(d)<<endl<<endl;;

    auto x = sin(3.14159);
    cout<<"size of auto that is double is: "<<sizeof(x)<<endl<<endl;

    auto y{sin(3.14159)};
    cout<<"size of auto that is double is: "<<sizeof(y)<<endl;

    cout << typeid(y).name() << endl;

    return 0;
}

I get the following output:

$ ./main 
size of int is: 4
size of float is: 4
size of double is: 8

size of auto that is double is: 8

size of auto that is double is: 16
St16initializer_listIdE

I think that the "auto y" is not actually being assigned double, but one of these: http://en.cppreference.com/w/cpp/utility/initializer_list

It says "An object of type std::initializer_list is a lightweight proxy object that provides access to an array of objects of type const T. "

So most likely the extra space is used to store a pointer and the size of the vector, or something like this.

Chris Beck
  • 15,614
  • 4
  • 51
  • 87