g++ - What happens if you don't return a value in C++? -


yesterday, found myself writing code this:

somestruct getsomestruct() {     somestruct input;      cin >> input.x;     cin >> input.y; } 

of course forgetting return struct created. oddly enough, values in struct was returned function got initialized 0 (when compiled using g++ is). coincidence or did somestruct created , initialized somewhere implicitly?

did somestruct created , initialized somewhere implicitly?

think how struct returned. if both x , y 32 bits, big fit in register on 32-bit architecture, , same applies 64-bit values on 64-bit architecture (@denton gentry's answer mentions how simpler values returned), has allocated somewhere. wasteful use heap this, has allocated on stack. cannot on stack frame of getsomestruct function, since not valid anymore after function returns.

the compiler instead has caller tells called function put result (which somewhere on stack of caller), passing called function hidden pointer space allocated it. so, place being set 0 on caller, not on getsomestruct function.

there optimizations "named value return optimization" copies can elided. so, had used missing return, result created directly on space allocated caller, instead of creating temporary , copying it.

to know more happening, have @ caller function. initializing (to zero) "empty" somestruct later assign return value of getsomestruct function? or doing else?


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -