Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

c++ - Unable to change values in a function

I'm starting with developing, sorry about this newbie question.

I need to create a function that swap values between 2 vars.

I have wrote this code, but no changes are made in vars, What should I change? What is my mistake?

#include <iostream>
using namespace std;

void swap_values( int x, int y);
int main(void) {
   int a,b;    
   a = 2;   
   b = 5;  
   cout << "Before: " << a << " " << b << endl; 
   swap_values( a,b );   
   cout << "After: " << a << " " << b  << endl;   
}  
void swap_values( int x, int y ){
   int z;
   z = y;
   y = x;
   x = z;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to pass the variables by reference:

void swap_values( int& x, int& y )
{
   int z;
   z = y;
   y = x;
   x = z;
}

pass-by-value and pass-by-reference are key concepts in major programming languages. In C++, unless you specify by-reference, a pass-by-value occurs.

It basically means that it's not the original variables that are passed to the function, but copies.

That's why, outside the function, the variables remained the same - because inside the functions, only the copies were modified.

If you pass by reference (int& x, int& y), the function operates on the original variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...