1

So I am pondering this question (this is a homework/exam review problem):

Write down an equivalent expression for a[j++] = ++i; without using pre/post increment operators. If no such expression can be provided explain why.

I was able to come up with the following:

a[j] = i+=1;
j+=1;

I can't think of a way to increment j within a[] as a post increment other than using j+=1; afterwards which I believe would lead to the answer of no such expression can be provided (because its two lines of code instead of one) and just explain that you can't post increment without the post increment operator.

Am I missing anything or am I correct? I just wanted to double check. Thanks in advance.

EDIT: Thanks to @James McNellis he provided a way using a[(j+=1)-1] = (i+=1);

gideon
  • 19,329
  • 11
  • 72
  • 113
Grant
  • 532
  • 2
  • 7
  • 21

4 Answers4

11

This is horrible and ugly, but here it is anyway:

a[(j += 1) - 1] = (i += 1);
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 3
    Correct on both counts. It's horrible, but it's the right answer. – SLaks Feb 23 '11 at 03:53
  • 4
    Believe me I know it is ugly and you would never do it, but what can you expect from a Computer Science Exam... Wouldn't test you on actual programming knowledge but rather try and trick you... Thank you for the answer though! – Grant Feb 23 '11 at 03:57
2

If you know that i won't wrap around to zero, one solution that comes to mind is this:

(a[j] = i += 1) && (j += 1);
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • I assume i starts at zero and increments from there. Though thank you for another way to accomplish the same thing. Obviously easiest is using the post/pre increment operators but it is an exam so they gotta try and trick you... – Grant Feb 23 '11 at 04:18
0

Does the comma operator count?

a[j] = i + 1, j += 1, i += 1;

It's like three separate lines of code... but technically one. (I know the second i += 1 is unnecessary, but I wrote it for consistency.)

Marlon
  • 19,924
  • 12
  • 70
  • 101
0

Equivalent expressions that don't even use += are

(a[j] = i = i + 1, j = j + 1, a[j-1])

and

(i = i + 1, j = j + 1, a[j-1] = i)
Jim Balter
  • 16,163
  • 3
  • 43
  • 66