- Code: Select all
if (val1 > val2)
temp = val1;
val1 = val2;
val2 = temp;
Works in all cases, by avoiding the use of a holding variable altogether i can't deal with 0 difference problems. In this case where i'm comparing if one is larger than the other and swapping it's not a problem as there's always a difference to initiate a swap, but if i was purely wanting to swap the integers it wouldn't work if the numbers were the same (as i'd get 0's).
Therefore, it's neat, but i'm not sure that it's the best answer. Although you guys are the ones to tell me if that's a good way to analyse the code and decide on it's worth (by judging it's universal usage potential)
Also, now i'm going to feel everything i write is awful because i don't know enough to judge it as i'm not thinking of a bigger picture, more does it run or do i get errors. It's sorely tempting to just post every exercise solution i feel unsure about (so yes in this case but not in that "is a number odd or even" as i'm happy with that) as i've no peer group or teacher to quiz for help.
It's very difficult to apply Occam's razor when you're working on your own work as a total beginner who cheers (metaphorically) every time code runs fine (and does what i wanted) without me having to fix anything. I don't know enough....and it's going to take some time to get my head in the right space for breaking down problems and fixing them neatly.