Please help, C++ Swap function not working.

Hey guys, I'm stuck on a homework program I'm supposed to type up.

Basically, the user should input a value that stores in the "first" variable. Then the user inputs a second value that is stored in the "second" variable. Then the program should call a swap function that will swap the first value and store it in the "second" variable, and vice versa.
(The formal parameters are supposed to be named number1 and number2 as I included).

Here is my program:
---------------------------------------

#include "stdafx.h"
#include <iostream>
using namespace std;



void swap(float, float);

int main()
{
float first;
float second;

cout << "Enter the first number then hit enter." << endl;
cin >> first;

cout << "Enter the second number then hit enter." << endl;
cin >> second;

cout << endl;

cout << "You input the numbers as " << first << " and " << second << "." << endl;
swap(first, second);
cout << "After swapping, the first number has the value of " << first << " which was the value of the second number." << endl;
cout << "The second number has the value of " << second << " which was the value of the first number." << endl;


system("pause");
return 0;
}

void swap(float number1, float number2)
{
float x = number1;
number1 = number2;
number2 = x;
}


Thank you in advance.
I don't mean to double post, but I actually just corrected the problem with pointers. My new question is, is there an alternate way of doing this in the swap function?
Yes, but it only works with integral types:

1
2
3
number1 ^= number2;
number2 ^= number1;
number1 ^= number2;


However, it's usually slower than just using a temporary, since the compiler can optimize that function for you, but usually has a harder time optimization the random xors.
Oh I gotcha, what do you mean by 'integral types'? I apologize, I'm not too advanced in C++ and I enjoy learning more.
Integral being the adjectival form of "integer". So ints, chars, etc.
You could also use references to accomplish the swap, like the std::swap() function does.
bitwise operators are more efficient so you might want to use them in your code :)
also theres generally no advantage to using floats, so i would just use doubles for more precision :)
bitwise operators are more efficient so you might want to use them in your code :)


Not really.

theres generally no advantage to using floats, so i would just use doubles for more precision


Floats use less memory. Although if precision is important, then yeah doubles would be the way to go.
Topic archived. No new replies allowed.