c++ - Function argument evaluation order -
this question has answer here:
i'm confused in order function arguments evaluated when calling c++ function. have interepreted wrong, please explain if case.
as example, legendary book "programming windows" charles petzold contains code this:
// hdc = handle device context // x, y = coordinates of output text char szbuffer[64]; textout(hdc, x, y, szbuffer, snprintf(szbuffer, 64, "my text goes here")); now, last argument is
snprintf(szbuffer, 64, "my text goes here") which returns number of characters written char[] szbuffer. writes text "my text goes here" char[] szbuffer. fourth argument szbuffer, contains text written. however, can see szbuffer filled in fifth argument, telling somehow expression
// argument 5 snprintf(szbuffer, 64, "my text goes here") evaluated before
// argument 4 szbuffer okay, fine. case? evaluation done right left? looking @ default calling convention __cdecl:
the main characteristics of __cdecl calling convention are:
arguments passed right left, , placed on stack.
stack cleanup performed caller.
function name decorated prefixing underscore character '_' .
(source: calling conventions demystified) (source: msdn on __cdecl)
it says "arguments passed right left, , placed on stack". mean rightmost/last argument in function call evaluated first? next last etc? same goes calling convention __stdcall, specified right-to-left argument passing order.
at same time, came across posts this:
how arguments evaluated in function call?
in post answers (and they're quoting standard) order unspecified.
finally, when charles petzold writes
textout(hdc, x, y, szbuffer, snprintf(szbuffer, 64, "my text goes here")); maybe doesn't matter? because if
szbuffer is evaluated before
snprintf(szbuffer, 64, "my text goes here") the function textout called char* (pointing first character in szbuffer), , since arguments evaluated before textout function proceeds doesn't matter in particular case gets evaluated first.
in case it not matter.
by passing szbuffer function accepts char * (or char const *) argument, array decays pointer. pointer value independent of actual data stored in array, , pointer value will same in both cases no matter whether fourth or fifth argument textout() gets evaluated first. if fourth argument evaluated first, evaluate pointer data -- pointed-to data gets changed, not pointer itself.
to answer posed question: actual order of argument evaluation unspecified. example, in statement f(g(), h()), compliant compiler can execute g() , h() in order. further, in statement f(g(h()), i()), compiler can execute 3 functions g, h, , i in order constraint h() gets executed before g() -- execute h(), i(), g().
it happens in specific case, evaluation order of arguments wholly irrelevant.
(none of behavior dependent on calling convention, deals how arguments communicated called function. calling convention not address in way order in arguments evaluated.)
Comments
Post a Comment