Home > Back-end >  c why are my statements in if loop not executing
c why are my statements in if loop not executing

Time:10-18

I have a function that checks if a is more than b. My output is "ok", which means that the if statement is true but I don't understand why it doesn't swap a and b. (p is another variable in the function)

    if (a > b)
    {
        cout << "ok " << endl;
        swap(a, b);
        _bubbleUp(p);
    }
    else
        cout << "no " << endl;

My swap function

void swap(T a, T b)
{
    T temp = a;
    a = b;
    b = temp;
}

CodePudding user response:

Your swap function takes a and b by value, so it does not alter the passed variables.

In order for the change to propagate, you need to take the arguments by reference:

void swap(T& a, T& b)
{
  // ...

Or even better: just use std::swap() instead.

CodePudding user response:

This line: void swap(T a, T b)

When the compiler sees that, it actually creates a copy of a and b, it did not change the actual value of a and b.

You have to pass by reference: void swap(T& a, T& b) or use the standard std::swap

  • Related