#swapping variables

32 messages · Page 1 of 1 (latest)

pastel coyote
#
#include <iostream>
using namespace std;



void swap(int x; int y) {
    
    int temp;
    x = y;
    y = temp;
    
}


int main() {


   int x = 1;
   int y = 2;
   
   swap(x,y);

   cout<<x<<y<<endl;

    return 0;
}```
errant whaleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

pastel coyote
#

It is giving errors

honest pebble
#

what is the expected behaviour? your function does not modify any variables passed to it by the caller

pastel coyote
#

Can you explain?

#
main.cpp:6:16: error: expected ‘)’ before ‘;’ token 6 | void swap(int x; int y) { | ~ ^ | ) main.cpp:6:23: error: expected initializer before ‘)’ token 6 | void swap(int x; int y) { | ^ ```


The error
tame grove
#

;

honest pebble
#

you aren’t supposed to have that semicolon there

#

in function declarations parameters are comma-seperated

pastel coyote
#

Oh

#

I'm dumb.

honest pebble
#

is this your first time writing a program?

#

there are other issues

tame grove
#

so shouldn't be first time

honest pebble
#

your function only modifies its own local copies of its arguments, not the versions you see printing out

pastel coyote
honest pebble
#

well you have to pass the variable by pointer or reference

#

do you know what those are

pastel coyote
#

Yeah

honest pebble
#

you are currently using the 2nd behaviour, you want the first one

pastel coyote
#
void swap(int *x, int *y){
   int temp;
   x = temp;
   x = y;
   y = temp;
}```

Something like that?
#

Ahh , pointers are hard

honest pebble
#

int* temp

pastel coyote
#

!solved

errant whaleBOT
#

Thank you and let us know if you have any more questions!

#

[SOLVED] swapping variables

honest pebble
#

now try to do it without the temp

pastel coyote
#
int temp = x*;
x* = y*;
y* = temp;```
pastel coyote