DEV Community

Discussion on: Terrible interview question: Swap variables without a temporary

 
lazarljubenovic profile image
Lazar Ljubenović

It depends on the language, but when talking about bit-level algorithms and pointers, people usually have C/C++ in mind. It will work properly if you use unsigned integers in Standard C, because adding and subtracting (unsigned) integers is defined by assuming modular arithmetic.

If you leave the default int type, which is a signed integer, a compiler might optimize something away and break the formula in case the overflow occurs.

Thread Thread
 
itr13 profile image
Mikael Klages

No, because (a+b)%c equals ((a%c)+(b%c))%c

Same with subtracting.

 
nikodannemiller profile image
Niko Dannemiller

I don't have much experience with pointers but from what I've played around with it might. I think it will have to do with your compiler and how much memory is available.

Thread Thread
 
nikodannemiller profile image
Niko Dannemiller

That's a good point. I've assumed that it will just roll over cleanly into negatives or roll down into positive (if both numbers are large negatives) but you're right some compilers in that case.

Thread Thread
 
lazarljubenovic profile image
Lazar Ljubenović

Could be. It's been a reeeeally long time since I've written anything in C or Assembly, so can't speak from the first hand at the moment, unfortunately.

Thread Thread
 
nikodannemiller profile image
Niko Dannemiller

S'all good. I'm still in Uni so outside of little side projects I only really know what professors have brought up. Might ask one about this problem.