Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (int_1 += *pointer++ = int_2++) < int_3 mean?

Tags:

c

expression

I was reading this earlier answer which had a piece of C code I couldn't understand. It essentially looks like this:

if((int_1 += *pointer++ = int_2++) < int_3) continue;

I can break it down to something like this -

What does this mean? I can get up to about this point:

if((int_1 = int_1+ *pointer++ (unsure about this part))<int_3) continue;
like image 211
Aveeral Jain Avatar asked Dec 05 '22 15:12

Aveeral Jain


1 Answers

So for starters, this is really, really bad C code. Like, horrible C code. Like, I've been coding in C for a long time and had to pull up an operator precedence chart because I've never encountered something like this terrible. So there's no reason to write something like this - certainly not in production code, and hopefully not as part of a class because you shouldn't never need to know this particular quirk of operator precedence (source: I teach CS for a living). I would go so far as to say that the source that you're referencing is Bad C Code That Should Never Be Written That Way.

But with that said, let's break it down! The core expression here is

(int_1 += *pointer++ = int_2++) < int_3

In that inner expression are two assignment operators, which have equal precedence and group from right-to-left. That means this is equivalent to

(int_1 += (*pointer++ = int_2++)) < int_3

This means

  1. Increment int_2 and store its old value.
  2. Store that value at the place pointed at by pointer, then advance pointer to the next location.
  3. Add that value to int_1.
  4. Then see whether that value is less than int_3.

There's no reason to do something like this. Just write

int val = int_2;
*pointer = val;
int_1 += val;

int_2++;
pointer++;

if (int_1 < int_3) {
    ...
}

So yeah! Don't write code like this. Ever. :-)

like image 100
templatetypedef Avatar answered Jan 01 '23 21:01

templatetypedef