Sunday, 15 September 2013

Why is this version of logical AND in C not showing short-circuit behavior? -



Why is this version of logical AND in C not showing short-circuit behavior? -

yes, homework question, i've done research , fair amount of deep thought on topic , can't figure out. question states piece of code not exhibit short-circuit behavior , asks why. looks me exhibit short-circuit behavior, can explain why doesn't?

in c:

int sc_and(int a, int b) { homecoming ? b : 0; }

it looks me in case a false, programme not seek evaluate b @ all, must wrong. why programme touch b in case, when doesn't have to?

this trick question. b input argument sc_and method, , evaluated. in other-words sc_and(a(), b()) phone call a() , phone call b() (order not guaranteed), phone call sc_and results of a(), b() passes a?b:0. has nil ternary operator itself, absolutely short-circuit.

update

with regards why called 'trick question': it's because of lack of well-defined context consider 'short circuiting' (at to the lowest degree reproduced op). many persons, when given function definition, assume context of question asking body of function; not consider function look in , of itself. 'trick' of question; remind in programming in general, in languages c-likes have many exceptions rules, can't that. example, if question asked such:

consider next code. sc_and exibit short-circuit behavior when called main:

int sc_and(int a, int b){ homecoming a?b:0; } int a(){ cout<<"called a!"<<endl; homecoming 0; } int b(){ cout<<"called b!"<<endl; homecoming 1; } int main(char* argc, char** argv){ int x = sc_and(a(), b()); homecoming 0; }

it clear you're supposed thinking of sc_and operator in , of in own domain-specific language, , evaluating if call sc_and exhibits short-circuit behavior regular && would. not consider trick question @ all, because it's clear you're not supposed focus on ternary operator, , instead supposed focus on c/c++'s function-call mechanics (and, guess, lead nicely follow-up question write sc_and short-circuit, involve using #define rather function).

whether or not phone call ternary operator short-circuiting (or else, 'conditional evaluation') depends on definition of short-circuiting, , can read various comments thoughts on that. mine does, it's not terribly relevant actual question or why called 'trick'.

c short-circuiting

No comments:

Post a Comment