1

I was wondering if was possible to update a value AFTER the line excutes, similar to:

int age = 10;
Console.WriteLine(age++);

outputs 10, but age becomes 11 right after.

My goal is to have something like:

int offset = 1;
Console.WriteLine(offset += 4);

But having the aforementioned behavior.

Edit: I know that you can always do it in 2 lines, but I was wondering / hoping you could do it in one.

Mike
  • 805
  • 2
  • 10
  • 16

4 Answers4

5

Update the value after calling the function:

int offset = 1;
Console.WriteLine(offset);
offset += 4;

You see:

Console.WriteLine(age++);

Is in essence the same as:

Console.WriteLine(age);
age += 1;
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 3
    +1 cool solution... never would have thought of posting this for real :-) – Yahia Jan 30 '12 at 20:37
  • so there's no way to do it inline? – Mike Jan 30 '12 at 20:38
  • 1
    @Yahia - Looks like Robert Harvey had the same though ;-) – Oded Jan 30 '12 at 20:38
  • 1
    @Mike - No. There is no language support for it. – Oded Jan 30 '12 at 20:39
  • @Oded I see... gave him +1 too in hope that he won't try to kill anyone :-) – Yahia Jan 30 '12 at 20:42
  • 2
    @Mike - Why try to get everything in one line? It can make for truly unreadable lines. – Oded Jan 30 '12 at 20:42
  • @oded learned a new word (mentch) - always like to learn something new :-) – Yahia Jan 30 '12 at 20:44
  • the line itself isn't too long, plus there are a lot of lines in a row that would use it, so I was hoping to trim down all the extra lines. I agree that if I was working on a team project, or where anyone else would be using/reading it, separating the lines is a much better idea, but in this case it's only me, and for some reason having that small updating line right after makes me cringe a little. – Mike Jan 30 '12 at 20:47
  • @Mike; Stop cringing. One day you will look at your old code and cringe because you put it all on one line. – AMissico Jan 30 '12 at 20:56
3

You're going to make the developers who have to maintain your code later much happier if you just do it the old-fashioned way:

int offset = 1; 
Console.WriteLine(offset); 
offset += 4;

I'd kill the person who tried to inline this, and make me puzzle it out. Seriously.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
1

As far as I am aware, you are unable to overload the ++ operator on integers to achieve the result that you want. You also cannot nest the ++ operator to post increment multiple times. A similar question was asked here:

C/C++ Post-increment by more than one

The general consensus is that you just have to use the extra line, and write

Console.WriteLine(offset);
offset += 4;
Community
  • 1
  • 1
3Pi
  • 1,814
  • 3
  • 19
  • 30
0

You can do it if you cheat.

I recommend against it for general style and good sense purposes; but it is possible to combine all that into one line:

Console.WriteLine("{0}", offset, offset += 4);
Tremmors
  • 2,906
  • 17
  • 13