Paul T. Paul T. - 3 days ago 6
C++ Question

structinit with list of two ints is reduced to one int

I tried to initialise a struct with variables. but in case i use type name = (values...) its only using the last element to initialise. it doesn't looks right for me but i don't know if its undefined behaviour, a compiler bug or something else. I would except a error message or initialise with more elements.

code:

struct funct {
funct(int i)
{
std::cout << "init with one\t" << i << std::endl;
}
funct(int i, int j)
{
std::cout << "init with two\t" << i << "\t" << j << std::endl;
}
};

int main() {
funct tempa = funct(42);
funct tempb = 43;
funct tempc = funct(44, 45);
funct tempd = (46, 47); // thats the compiling thing
return 0;
}


output:

init with one 42
init with one 43
init with two 44 45
init with one 47


why is it this way and not init with 2 or a compileerrormessage?

compiler: g++ (GCC) 5.3.0

Answer

Like Ben said, it's the comma operator that's causing an issue.

http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins

by doing a = (b,c) you are effectivly setting a = c and discarding b

Comments