re: Terrible interview question: Swap variables without a temporary VIEW POST

re: Yeah, this is one of the standard answers for numerical data. You can do similar things with multiplication/division (but you'll have issues there ...

With pointers, does overflow affect this kind of swapping?

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.

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.

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.

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.

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.

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

Same with subtracting.

code of conduct - report abuse