2

I came across this line of code written in C that confuses me coming from a JavaScript background.

short s;
if ((s = data[q])) 
    return s;

Is this assigning s to data[q], and if it equals true/1, return s?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cocacrave
  • 2,453
  • 4
  • 18
  • 30
  • 3
    Yes, you are right. This has been discussed [here](http://stackoverflow.com/questions/151850/why-would-you-use-an-assignment-in-a-condition) – byxor Sep 02 '16 at 10:14
  • basically it returns s as long as data[q] is != 0. In C, everything except 0 is true. (of course s is assigned data[q]). – Nidhoegger Sep 02 '16 at 10:15

3 Answers3

11

Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false.

it would be the same as

if ((s = data[q]) != 0) return s;
Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • 2
    "Evaluated as 1" is really confusing, it's more like "any non-zero value will be considered to be true". – unwind Sep 02 '16 at 10:18
7

Your code is assigning data[q] to s and then returns s to the if statement. In the case when s is not equal to 0 your code returns s otherwise it goes to the next instruction.

Or better said it would expand to the following:

short s;
s = data[q];
if (s != 0)
    return s; 
Adrian Jałoszewski
  • 1,695
  • 3
  • 17
  • 33
2

Basically C evaluates expressions. In

s = data[q]

The value of data[q] is the the value of expression here and the condition is evaluated based on that.

The assignment

s <- data[q]

is just a side-effect.


Read this [ article ] on sequence points and side-effects

sjsam
  • 21,411
  • 5
  • 55
  • 102