Paul T. Paul T. - 1 year ago 88
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.


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;


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 Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download