Search code examples
cansi-c

What is this code block doing ? (u > 0) - (u < 0)


if (abs(u) > Vdc)
    u = Vdc*((u > 0) - (u < 0));

This code is in C considering we enter the if condition what will happen ? Vdc = 24; consider any arbitrary value of u for an explanation


Solution

  • If u > 0 the statement will become 1 - 0 (true - false) = 1. If u < 0 it will become -1. If it is zero, it will become 0 as well. So basically it is returning the "sign" of u (or more precisely 1 with corresponding sign). The overall code snippet is for clamping u between +Vdc and -Vdc. (As suggested, it will work only for positive Vdc).