Home > Software design >  Whats the order of operations with respect to 'return' in C
Whats the order of operations with respect to 'return' in C

Time:11-29

I was shocked by the output of this... been coding in C for a few years now. Could someone explain a possible use case? Seems like it should be a compiler warning.

#include <stdio.h>

int chk(int var)
{
    return var  ;
}

int main (void)
{
    int a = 1;

    a = chk(a);

    printf("var is: %d\n", a);

    return 0;

}

var is: 1

CodePudding user response:

From the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

So the return statement in the function

int chk(int var)
{
    return var  ;
}

returns the value of the parameter var before incrementing it. So acrually the postfix incrementing in this return statement does not have an effect and is equivalent to

return var;

That is the function returns the original value of the argument expression.

The function would be more meaningful if for example instead of the postfix increment operator it used the unary increment operator like

int chk(int var)
{
    return   var;
}

In this case the function returns incremented value of the the value of the argument expression.

CodePudding user response:

In the computing model the C standard uses, return var ; has a main effect of return the value of var and a side effect of incrementing var. The value of var used for the return is the value prior to the increment.

Because var is a parameter of the function, incrementing it affects only the value of the parameter. It does not affect the argument a in the calling routine.

Seems like it should be a compiler warning.

Yes, this code performs a side effect that has no use, which could suggest a mistake by the author, so it is reasonable a compiler would warn about it.

  • Related