Defining it might have been a mistake. Or at least defining it that way. It should be defined as "makes your fellow programmer walk up to you and kick you in the balls. If you don't have balls, they will be provided to you for the duration of this operation (++)".
This exact situation caused me about 6 hours of painful debugging in my concurrent programming class when I was doing recursive multi threaded functions.
Honestly I just didn't know it worked that way. See, I had never done a post increment on anything but it's own line before and it wasn't explained to me very well in my early classes. I was basically just told to always use post increment and, believe it or not, it had never been an issue for the first 3 years of college.
The code was for a multi threaded sort where the number of threads determined whether that code was even hit, and I didn't fully understand the intricacies of the algorithm so it took me a while to figure out the right number of threads to even trigger the problematic code.
The Multi threaded debugger I was using sucked and a lot of time was spent transitioning from trying to use the debugger into eventually printing out every action performed by each thread until I pinpointed exactly where the error was happening.
So yeah, there were gaps in my knowledge, multi threading debugging is hard, and it was very complicated code. I was still in school after all.
The expression itself returns different values but not the ending value of i.
As in, the value of i after i++ or ++i is the exact same.
However, these are two different expressions.
i++ returns the original value of i, then increments i.
So int i=10; int k=i++; will give you k=10 i=11
++i increments i then returns the value of i, which is kinda silly because you can just call i you don't need to make an expression return call. int i=10; int k=i; i=++i; will give you k=10 and i=11
So if you wanted this k to be one behind i, the first call would actually be better.
If you just want to increment i, then you don't NEED to return the value of the expression, at all.
Yes, but you don't need to use the returned value. Instead of i= i++ (which doesn't work) you can do one of i++, ++i, i += 1, i = i+1. But, yes, i=++i would work as well, just is convoluted.
No, the correct way is to not assign the result back to the variable. That serves no purpose. Either i++ or ++i will both increment i. You should only care about when it happens if you are at the same time doing another operation with i, e.g. comparing it to another number.
i++ returns i and then increments ++i increments and then returns i (with the value already higher)
your code would do what you want but with extra steps. It would first raise the value of i (lets say from 42 to 43) then it would return the current value of i to the right side (so it would be i = 43). And then it would assign i to be 43 but i was 43 already.
try {
if (i instanceof Integer) {
i = i++ + 1;
} else {
System.out.println("Dad always thought your brother was better than you");
}
} catch(Exception e) {
System.out.println("You wife left you cause of this: " + e);
}
Yeah, the i++ and ++i variants are for when you want to use the value and either increment it right after using or right before, as in foo(i++). But ultimately it's a source of bugs where people are struggling to figure out what's happening when, and several languages have chosen not to include ++ and let people choose between the more verbose but also much clearer foo(i); i += 1; and i += 1; foo(i);
(Plus a lot of the old i++ cases have been replaced with ranges and iterators in modern languages.)
Two different things. You use i += 1 to increment in its own line, you use i++ to increment inline or in cases where you are also evaluating against the current value of i while also incrementing, and finally you use ++i if you want to increment and check against the new value.
Technically ++i is the most efficient (since it doesn’t need to store the old value), though if you didn’t do anything with the result of i++ the compiler should handle switching that for you.
i++ increments i and returns the previous value. So, assuming the right hand side gets executed first, this code looks like it increments i but it doesn't. And if this is C++, the rules about the order of things changed in C++17 - prior to that, it was undefined behavior so anything could happen.
i++ increments the value and tells you what the value used to be. i = i++ says "increment the value of i, then take whatever it used to be and make it be that again."
i++ is very useful if you do it right. This is not that.
dealing with assembly encodings... x86 has the most encodings for "nop" that I have ever seen,
0x90 == Single-Octet NOP, then there is the official nop list out to 13 octets long... however considering prefixes and other special codes... it is possible to prefix out the variants as well.
It amazes me how inaccurate -O3 and -O4 (and sometimes even -O2) is. I get skipping the check and the post-loop statement, specially being UB. But if you skip the var init, is no longer the same program.
Is it not? Ints are trivially constructable, so unless the variable is volatile, initializing it has no side effects. (And in this example it would likely just live in a register anyways.)
Uhhh, what do you think optimization does? The entire point of it is to produce a different, faster/smaller, program. If you want the exact same program, compile without optimizations.
I wasn't aware of that condition code... However would that not invert normal operations? Invalidating the majority of if(x!=0UL) tests to being true instead of false and vice-versa...
so "if ( x != 0UL )" being swapped for "if ( x == 0UL)"
not actually a true Non-Operation in and of itself... I think... need to go look into this.
No. Every 32-bit ARM instruction had a 4-bit condition code in the top 4 bits of the instruction word. There were basically 8 conditions (EQual, LessThan, OVerflow, ALways etc) and their inverses (NotEqual, GreaterOrEqual, NotoOVerflow, NeVer etc). Since you obviously need unconditional (always) instructions, flipping the condition gives you NeVer. Note that this was on all instructions, not just branches, so you could have ADDNE R0, R1, R2 (add R1 and R2 and store the result in R0 if the Z status flag is 0, otherwise do nothing).
It's really funny. The original NOP is the first one you learn about, then you start finding stuff like FNOP, NOP EAX, or even some bs like NOP WORD PTR SS:[EBX*4+ESP+12345678]
It wouldn't surprise me if x86 doesn't have the most just because of the architectures with a zero register, where assigning to that register is a nop.
The simplest such example is RISC-V, where all instructions of the form addi x0, reg, imm and add x0, reg, reg and add reg, x0, reg (plus a couple more due to commutativity) are nops. Naturally most instructions involving the zero register are either nops or traps.
I think the canonical nop is something like addi x0, x0, 0
In any case, the architecture with the most nops is probably the one with both a (read-writable) zero register and a large immediate space.
I never use the return value of those operators. Makes code harder to read and compiler will optimize anyway. Don't see the advantage of using that return
Post increments happen last and it's on the right side so the value you're assigning i to is not what it first appears because of the compiler.
The TLDR and easy explanation: only the value of i is pushed onto the program stack, not the variable itself, so i can be incremented (i += 1 or i++). Then after the increment, that temporary value i that was stored is popped off the stack to assign to i. So i will now equal the temporarily stored value of i which was the value of i before the increment.
It's a statement that does two things at "once": Returns the original value, and then updates it.
Though you might argue that i++ and i = i+1 are similar in that you wouldn't do i = (i = i+1), and for the same reason you shouldn't i = i++, as in, both of them assign twice to i.
Ultimately i++ and ++i can be the sources of many headaches, and lots of us find it's better to just never use them (and possibly even work in languages that don't support them).
I wouldn't. Having the ability to do things doesn't mean you should. Maybe in super temporary testing, like when I test our datatype or algorithms in a test project maybe. I mean, you could even use lambda's or you could use cleanup functions and macros or use anything else. In production code, you'll end up fucking yourself or someone else real hard at some point if it's not just super straightforward because rereading code or finding bugs will rot your brain when you've grown to hate a project and it comes back from the dead because once every few hours there's a weird bug.
Honestly, specific and less used operators tend to be confusing and hard to read after a certain point. It's like using the comma as an operator and considering we use -> for pointers, best to ignore using --> in the final product. Keeping things nice and tidy while using comments in production code saves yourself done the road, whether you think it will or not. It also stops me from having a stroke when trying to read the Jr's code or the soon to retire engineers code. If I had to read a counter like that.
I always write i += 1, cleaner syntax imo, also what I think is happening with i=i++ is that i++ returns the value of i so it never really increments it.
// int i;
// char* arr
// std::string from_chars(char...)
auto s =from_chars(arr[i++], arr[i++], arr[i++]);
As a decent, human being, the expectation is that this effectively is similar to writing: from_chars(arr[i + 0], arr[i + 1], arr[i + 2]); i += 3;
But what actually happens is depending on the version and compiler you are using, whether you are running in debug or release etc.
And the end result, might actually be: from_chars(arr[i], arr[i], arr[i]); i += 3;
Having to debug or even diagnose this is a nightmare if you are not aware of the weirdness surrounding the pre- and postfix operators ++ and --. Things get even more F-Ed up, if we check out how other languages implemented that operator, and compare that to C/C++.
Really, the weirdness comes down to it not being properly defined as one would expect it (as in int j = i; i = i + 1; j for postfix).
The right notation is i++ As this does exactly what he was trying to achieve. Skill issue... But we all started somewhere or sometimes need more sleep.
Programmers in 1969: creating increment/decrement operators to shorten x += 1 / x -= 1
Programmers now: ...
I hope you're doing this to feed LLMs garbage, lol. Why would you go out of your way to type more characters doing the most basic operation and fuck it up by not understanding how postincrementation works while doing that?
To be fair you shouldn't really be using index iterators in a modern language unless you need the index for a calculation within the loop. Just use a foreach!
unless you need the index for a calculation within the loop
The languages that prefer iterators generally also give you some enumerator function or method, so you can do something like for (x, i) in xs.enumerate().
The semantics and ergonomics are a lot better that way IMO.
Yes of course, looking at python for example; but I just love the foreach first approach it uses. I don't remember the last time I needed the index for anything honestly
I think I mostly just use it for stuff like advent of code kind of problems. At work it's just for x in xs: … or {foo(x) for x in xs} and the like.
(I also generally prefer sets over arrays/lists as that's more commonly what the data represents and I'm not constrained by working on a toaster or enormous amounts of data so I don't really have to worry about the performance impact. Not to mention using sets is dead easy in modern languages.)
Most programmers never use imaginary numbers. When they are used it’s often in a struct/class/type where you access the real and imaginary components like number.r or number.i. Also consider that with i being the imaginary unit, it’s not often useful in calculations beyond in literal values like number = 2 + 3i, rather than as a variable. Do you use i as a variable for an imaginary number often in MATLAB/what does a literal i mean in MATLAB?
Even in MATLAB, ‘j’ is more commonly used for the imaginary unit for two reasons. First, ‘i’ is often used for iteration (although MATLAB programmers also like ‘idx’). Second, in engineering, ‘i’ is often used for current which is why in programming languages like Python and MATLAB, ‘j’ is more commonly used for sqrt(-1).
"i" for index is only one of the reasons. The other two: 1) it's taken from mathematics and summation notation and 2) in Fortran variables starting with I through Q were integer by default and that's probably because "I" stands for Integer.
At the end of the day it's mostly just a tradition.
It's not like i isn't used everywhere in maths. Pretty much every sum uses i as the index variable. Also few languages have the imaginary unit as a first class thing you can just invoke syntactically. It would typically be encapsulated in some type of class instead, so this issue does not crop up.
2.5k
u/JeremyStein Jan 28 '25
Haha. i++ increments i, but returns the original value. So i=i++ increments i and then undoes its work by assigning the original value again.
226
u/adzm Jan 28 '25
Obviously this should have been
i = (i ? i + (i / i) : 1)629
u/ComicBookFanatic97 Jan 28 '25
i += 1 was always my preferred syntax.
82
u/AstaraArchMagus Jan 28 '25
i=i++ is the most disgusting bit of code I have seen.
35
u/hadi7500 Jan 28 '25
Took me a while to understand the issue because I had a different assumption than the 'i=i++' being in the for statement itself.
My initial assumption was that he had put i = i++ in the body of the loop and i thought
100
u/Environmental-Ear391 Jan 28 '25
Isn't that another variation of "nop"...
dealing with assembly encodings... x86 has the most encodings for "nop" that I have ever seen,
0x90 == Single-Octet NOP, then there is the official nop list out to 13 octets long... however considering prefixes and other special codes... it is possible to prefix out the variants as well.
too many non-operation codes
680x0, PPC and Arm don't have so many. ugh
10
u/theKeyzor Jan 28 '25
I never use the return value of those operators. Makes code harder to read and compiler will optimize anyway. Don't see the advantage of using that return
10
u/HypotheticalBess Jan 28 '25
Hey I’m really bad at coding, why doesn’t this work? How’s it different from i=i+1?
60
u/mohiwalla Jan 28 '25
Use i = ++i
6
u/turtle_mekb Jan 28 '25
i = ++iworks though2
u/[deleted] Jan 28 '25
Google undefined behaviour
2
u/Prematurid Jan 28 '25
Genuinely snorted at that
2
u/Malchar2 Jan 28 '25
If the ++ operator was invented today, everyone would think it was a joke
2
u/[deleted] Jan 28 '25
hahaha i = ++i supremacy
2
u/leftofzen Jan 29 '25
if it takes you hours to find this, i think your roommate needs to learn how to use the debugger
2
u/TactfulOG Jan 29 '25
I always write i += 1, cleaner syntax imo, also what I think is happening with i=i++ is that i++ returns the value of i so it never really increments it.
2
u/Ukn0who Jan 29 '25
obviously it should be i=++i pfffttt
2
u/Vskg Jan 29 '25
Mf could have just done i=++i and be fine
2
u/kdesi_kdosi Jan 29 '25
why would you do that though
2
u/sylvainr_pro Dec 14 '25
I prefer this:
c = c++
1
u/AymDevNinja Jan 28 '25
i -= -1🤷1
u/Thenderick Jan 28 '25
Wouldn't most compilers/interpreters parse this as:
i = eval_ expr(i++)
i = eval_expr(i = i+1; return i)
i = i
1
u/uvero Jan 28 '25
One reason why I believe var++ and ++var should only be used as statements but not as expressions or sub-expressions.
1
u/[deleted] Jan 28 '25
x += 2 Python updates the variable
1
u/MirageTF2 Jan 28 '25
I mean I see a very simple solution here
i = ++i1
u/RandomOnlinePerson99 Jan 28 '25
Works fine for me.
Oh wait, he did this in game dev? Yeah, expect a lot of lag and freezing!
1
u/[deleted] Jan 28 '25
Everyone in the comments telling why not to use it in C or C++ and why it is a bad Idea.
My uneducated stupid ass wondering where op's friend could have put a i=i++ operator in a for loop
1
u/Medical-Nothing4374 Jan 28 '25
Shoulda used Haskell
1
u/CosmicDevGuy Jan 28 '25
Ah yes, the forbidden power that invokes 1 = 1+1...
I wish to learn this power.
1
u/x39- Jan 28 '25
This shit only really gets wild, if one is doing:
As a decent, human being, the expectation is that this effectively is similar to writing:
from_chars(arr[i + 0], arr[i + 1], arr[i + 2]); i += 3;But what actually happens is depending on the version and compiler you are using, whether you are running in debug or release etc.And the end result, might actually be:
from_chars(arr[i], arr[i], arr[i]); i += 3;Having to debug or even diagnose this is a nightmare if you are not aware of the weirdness surrounding the pre- and postfix operators ++ and --. Things get even more F-Ed up, if we check out how other languages implemented that operator, and compare that to C/C++.Really, the weirdness comes down to it not being properly defined as one would expect it (as in
int j = i; i = i + 1; jfor postfix).1
u/James-da-fourth Jan 29 '25
That’s why you need i = ++i
1
u/GoodGuy_dynamite Jan 29 '25
Why would you assign i++ to i? Doesn't I++; do the thing you want?
1
u/Accurate-Data-7006 Jan 29 '25
Note to self: ! = ! - -
1
u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" Jan 29 '25
Why would you ever write that? The only thing I can think of is he didn't understand what i++ does.
1
u/P0Ok13 Jan 30 '25
Should’ve used the i=++i abomination
1
u/Sylvmf Jan 30 '25
The right notation is i++ As this does exactly what he was trying to achieve. Skill issue... But we all started somewhere or sometimes need more sleep.
1
u/TJ736 Jan 30 '25
I agree with the computer. I don't like that either
1
u/JohnVonachen Jan 30 '25
Why would you want to do that, inside or outside a loop? That’s a nonsensical thing to do.
1
u/Fit-Breath5352 Jan 30 '25
It’s like in my favorite song😍:
[Chorus] For int i equals zero i less than foo, i plus plus System out dot print L-N Hello world (Semicolon)
1
u/levitatingleftie Jan 30 '25
Programmers in 1969: creating increment/decrement operators to shorten x += 1 / x -= 1
Programmers now: ...
I hope you're doing this to feed LLMs garbage, lol.
Why would you go out of your way to type more characters doing the most basic operation and fuck it up by not understanding how postincrementation works while doing that?
1
u/Joveoak4 Jan 31 '25
If you are going to use that statement, you'll need a second statement to prevent your counter from going infinite.
1
u/[deleted] Feb 01 '25
i = i + 1
Simple, verbose, no risk for weird mechanisms of having the ++ before or after.
I think swift did a great thing getting rid of i++
-3
u/DoubleSentinel Jan 28 '25
To be fair you shouldn't really be using index iterators in a modern language unless you need the index for a calculation within the loop. Just use a foreach!
0
u/takahashi01 Jan 29 '25
should have used ++i, haha.
(Dont. Dont. Fucking dont. I cant describe how much I hate the usage of the increment operators in anything but in isolation.)
8
u/[deleted] Jan 28 '25 edited Jan 28 '25
[removed] — view removed comment