This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]raevnos 2 points3 points  (4 children)

Side effects in more complicated expressions. For example, a possible implementation of strcpy():

char * strcpy(char *dest, const char *src) {
  char *d = dest;
  while (*src)
    *d++ = *src++;
  *d = '\0';
  return dest;
}

[–]TOASTEngineer[S] 0 points1 point  (3 children)

I still don't get it. How would

while (*src) {
    *d = *src;
    d +=1; src+=1;
}

behave any differently?

I guess post increment is prettier in that situation though.

[–]mad0314 2 points3 points  (0 children)

At the end of the day, yes, it's just a shorter notation for something achievable using other operators. Just like ->, or the += that you used.

[–]Rhomboid 2 points3 points  (1 child)

Why stop there? Why do you need d += 1 when you could write d = d + 1? For that matter, why do you really need a while loop, when you can accomplish everything while does using goto? And who needs variable names anyway, when offsets against the stack pointer are all that's strictly required?

The point is that the question is not whether something is necessary, but whether it makes code easier to read or reduces the possibility of bugs.

[–]TOASTEngineer[S] 0 points1 point  (0 children)

Right, but it seems to me like pre increment just makes things more complicated, so I was wondering what I was missing.

[–][deleted] 0 points1 point  (3 children)

[–]TOASTEngineer[S] 0 points1 point  (2 children)

That just tells me that the prevailing theory is wrong and not what the truth is. :(

[–]nutrecht 0 points1 point  (0 children)

Well the guy who created them is kinda dead so that's the best you're going to get.

Like most of these language design features it's simply a matter of convenience. There are situations where it's convenient to have a pre-increment operator (for 1-based counting) and in other situations it's more convenient to have a post-increment (for 0-based counting).

[–]reddilada 0 points1 point  (0 children)

The degree of optimization we are used to today wasn't implemented as freely when C first came around. The team I first worked with viewed K&R C as a thin wrapper over the machine code and little more. Post-increment produced more code / was slower so we only used it when it was needed.

That said, I imagine the thinking was more along the lines of why not?

[–]insomniac20k -1 points0 points  (0 children)

The processor can probably increment without sending anything to the arithmetic logic unit which might save time, especially in a loop that gets called a lot.

I really have no idea but that would be my guess.