Ad
  • Custom User Avatar

    Thanks for the link, @hobovsky!

    I'll give it a read :)

  • Custom User Avatar
  • Custom User Avatar

    This is the approach I took too, except I moved mine into a macro to keep it a little more readable and re-usable:

    #define SWAP(x, y) (x ^= y ^= x ^= y)
    
  • Custom User Avatar

    While I agree with the idea behind moving the strlen into a variable to avoid it being repeatedly called, I don't agree with having that live in the loop. Having multiple variable declarations in a loop makes the loop look more complicated than it is, without any significant pay-off at compilation.

    It reads much better to have the line moved out of the loop entirely, and also given a more descriptive name such as string_length.

  • Custom User Avatar

    Division can be an incredibly expensive operation, so you'll want to avoid doing it as much as possble. To help with this, you can move the result of (int)strlen(str)/2 into a variable and re-use that variable, otherwise the division operation will be performed every iteration.

    Also, while we're on the subject of "division by 2," it's a lot more efficient to use bit-shifting whenever you're dividing or multiplying by multiples of two. Division could take up to 30-60 CPU cycles to perform, compared to bit-shifting which only takes a single cycle.

    n >> 1 // Divides by 2
    n << 1 // Multiplies by 2
    
    

    This works because you're shifting the bits over into the next adjacent digit place, and since each digit place in binary acts as a multiple of two, it can divide or multiply by two:

    1 << 0 // Results in 1 (0001). You'd never really do this, it's just to show that shifting by 0 doesn't perform a shift.
    1 << 1 // Results in 2 (0010)
    1 << 2 // Results in 4 (0100)
    1 << 3 // Results in 8 (1000)
    
    
  • Custom User Avatar