Unable to change values in a function - c++

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;
}

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.

You need to understand that by default, C++ use a call-by-value calling convention.
When you call swap_values, its stack frame receives a copy of the values passed to it as parameters. Thus, the parameters int x, int y are completely independent of the caller, and the variables int a, b.
Fortunately for you, C++ also support call-by-reference (see wikipedia, or a good programming language design textbook on that), which essentially means that the variables in your function are bound to (or, an alias of) the variables in the caller (this is a gross simplification).
The syntax for call-by-reference is:
void swap_values( int &x, int &y ){
// do your swap here
}

you are passing by value. you can still pass by value but need to work with pointers.
here is the correct code needed:
void swap(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
void main() {
int a = 23, b = 47;
printf("Before. a: %d, b: %d\n", a, b);
swap(&a, &b);
printf("After . a: %d, b: %d\n", a, b);
}
also a small document that explains "by reference" vs "by value" : http://www.tech-recipes.com/rx/1232/c-pointers-pass-by-value-pass-by-reference/

Related

How can i increase value of x in function?

C++ Program: - I know that in the function definition, x is not passed so it would get error message but i want to increase in function, so what can i do?
#include <iostream>
using namespace std;
fun(int& p)
{
cout << p;
x++;
}
int main()
{
int x = 15;
int c = 1;
fun(c);
cout << x;
return 0;
}
The value of variable x is undefined for fun() and you should go through a book for basics.
The only method if you just want to manipulate the same variables, is using reference variables as parameters and then you can directly modify its original values.
Refined version of your program for accessing and manipulating the data with functions:
#include <iostream>
void fun(int &, int &);
int main(void) {
int x = 15;
int c = 1;
fun(c, x); // c is printed "1" and x increments with 1
std::cout << x << std::endl; // new value of x prints
return 0;
}
void fun(int & p, int & x) {
std::cout << p << std::endl;
x++; // increments original x
}
Note: Alternatively, you can declare your required variable in global scope by putting them outside of all the functions and underneath the header declaration, so that they'll be visible to the entire program but remember that you must need to use reference for changing the variable values for the whole program.
You can either set x as a global variable or you can also pass it to your function.
fun(int &p, int &x) and then call it from main.

Function returning unexpected struct values

I am completely new to structs and user defined datatypes, and i was trying to create a function that returns a struct:
The problem is highlight by the comment:
#include <iostream>
using namespace std;
struct num {
int n[2];
};
num func( num x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
return x;
}
int main() {
int x,y;
num s1;
cout << "enter: ";
cin >> x >> y;
func(s1,x,y);
cout << s1.n[0] << "\n" << s1.n[1]; // THIS GIVES ERROR
cout << func(s1,x,y).n[0] << "\n" << func(s1,x,y).n[1]; // THIS DOENST GIVE ERROR
return 0;
}
I understand that second method makes sense and returns the struct variable. then putting a dot addresses the inner variable of struct.
But i dont understand why first method fails, or gives odd output. The function has done its job, ie made s1.n[0] = x + y and s1.n[1] = x*y
Now, printing s1.n[0] should print x + y only. How can we check and correct the internal workings of the function?
You have to assign the returned value to the structure object in main
s1 = func(s1,x,y);
Inside the body the function deals with a copy of the original object. It does not change the original object because it is passed by value.
Another approach is to pass the structure by reference
void func( num &x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
}
In this case in main you could just write
func(s1,x,y);
Or you could use even so-called C approach of passing by reference
void func( num *x, int a, int b) {
x->n[0] = a+b;
x->n[1] = a*b;
}
and call it like
func( &s1, x, y );
As for this statement
cout << func(s1,x,y).n[0] << "\n" << func(s1,x,y).n[1];
then you access data members of two temporary objects returned by the two calls of the function. After executing this statement these temporary objects will be deleted.
It looks like you are never assigning the return value of func(). Your function returns the struct, but you are never assigning it. To fix this, you should be able to simply say: s1 = func(s1,x,y); This will assign the modified version of the struct to the s1 variable.
Alternatively, you could rewrite func() to accept a pointer to the struct. This would allow you to modify the struct without having to return it:
void func( num *x, int a, int b) {
x->n[0] = a+b;
x->n[1] = a*b;
}
Then you would just change your call to func() to say: func(&s1, x, y);
You are not passing your struct by reference, hence the result. Try the following:
void func(num &x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
}
There's no need for the function to return anything since your struct is passed by reference and it will be changed anyway. Void would fit better.
This is because you have passed the struct by value while your intentions look like you want to pass by reference.
Check this link : http://courses.washington.edu/css342/zander/css332/passby.html
num func( num &x, int a, int b)
should fix your problem

Functions in different files not working properly

I made a program that calls this function. I know this because "Int Strength has been called" appears in the output box. However, it will not change the values that I tell it to do.
I want it to get integer values from main(), then use them and return the new values.
I am using a header file that only contains "int strength(int a, int s, int i)"
int strength(int a, int s, int i)
{
using namespace std;
cout << "Int Strength has been called" << endl;
a = a + i;
s = s - i;
return a;
return s;
}
Multiple errors. Firstly, if you want the arguments to be modified (more precisely, the modification being effective out of the scope of the function), you have to pass the values by reference:
int strength(int &a, int &s, int &i)
Second, you seem to be concerned about return a; return s; returning two values. It doesn't - the very first return encountered exits the function immediately.
The values only change within the function. Variables are passed by value not reference.
Use references as the parameters.
int strength(int& a, int& s, int& i)
You're passing by value. You need to pass a pointer to the memory allocated in the caller that contains the data you wish to modify.
void strength(int *a, int *s, int i)
{
using namespace std;
cout << "Int Strength has been called" << endl;
*a += i;
*s -= i;
}
Then call it thusly:
a = 1;
s = 2;
i = 3;
strength(&a, &s, i);

Classes - Get function - return more than one value

Let's suppose we have:
Class Foo{
int x,y;
int setFoo();
}
int Foo::setFoo(){
return x,y;
}
All I want to achieve is form my get function to return more than one value. How can I do this?
C++ doesn't support multiple return values.
You can return via parameters or create an auxiliary structure:
class Foo{
int x,y;
void setFoo(int& retX, int& retY);
};
void Foo::setFoo(int& retX, int& retY){
retX = x;
retY = y;
}
or
struct MyPair
{
int x;
int y;
};
class Foo{
int x,y;
MyPair setFoo();
};
MyPair Foo::setFoo(){
MyPair ret;
ret.x = x;
ret.y = y;
return ret;
}
Also, shouldn't your method be called getFoo? Just sayin...
EDIT:
What you probably want:
class Foo{
int x,y;
int getX() { return x; }
int getY() { return y; }
};
You can have reference parameters.
void Foo::setFoo(int &x, int &y){
x = 1; y =27 ;
}
You can't return more than one object per se, but what you can do is use either std::pair from <utility> or std::tuple from <tuple> (the latter only available in the latest C++ standard) to pack more than one value together and return them as one object.
#include <utility>
#include <iostream>
class Foo
{
public:
std::pair<int, int> get() const {
return std::make_pair(x, y);
}
private:
int x, y;
};
int main()
{
Foo foo;
std::pair<int, int> values = foo.get();
std::cout << "x = " << values.first << std::endl;
std::cout << "y = " << values.second << std::endl;
return 0;
}
You cannot really return multiple values in c++. But you can modify multiple values by reference
C++ does not allow you to return multiple values. You can return a type that contains multiple values. But you can only return one type from a C++ function.
For example:
struct Point { int x; int y; };
Class Foo{
Point pt;
Point setFoo();
};
Point Foo::setFoo(){
return pt;
}
You can use std::pair for two returned variables and std::tuple (C++11 only) for more of them.
You can not return more than 1 variable.
But you can do pass by reference, and modify that variable(s).
// And you pass them by reference
// What you do in the function, the changes will be stored
// When the function return, your x and y will be updated with w/e you do.
void myFuncition(int &x, int &y)
{
// Make changes to x and y.
x = 30;
y = 50;
}
// So make some variable, they can be anything (including class objects)
int x, y;
myFuncition(x, y);
// Now your x and y is 30, and 50 respectively when the function return
cout << x << " " << y << endl;
Edit: To answer your question on how to get: Instead of returning just 1 variable, you pass some variables, so your function can modify them, (and when they return), you will get them.
// My gen function, it will "return x, y and z. You use it by giving it 3
// variable and you modify them, and you will "get" your values.
void myGetFunction(int &x, int &y, int &z)
{
x = 20;
y = 30;
z = 40;
}
int a, b, c;
// You will "get" your 3 value at the same time when they return.
myGetFunction(a, b, c);

Can a function return more than one value? [duplicate]

This question already has answers here:
Returning multiple values from a C++ function
(23 answers)
Closed 1 year ago.
Can a function return more than one value directly (i.e., without returning in parameters taken by-reference)?
In the boost::tuple library, there's a function called tie that simplifies the process of getting information out of a returned tuple. If you had a function that returned a tuple of two doubles and wanted to load those into two local variables x and y, you could assign your function's return value to boost::tie(x, y).
Example:
#include <math.h>
#include <iostream>
#include <boost/tuple/tuple.hpp>
const double PI = 3.14159265;
boost::tuple<double, double> polar_to_rectangular(double radius, double angle)
{
return boost::make_tuple(radius * cos(angle), radius * sin(angle));
}
int main()
{
double x;
double y;
boost::tie(x, y) = polar_to_rectangular(4, (45 * PI) / 180);
std::cout << "x == " << x << ", y == " << y << std::endl;
return 0;
}
Yes - have your function return a struct. Or return the values via reference parameters.
struct A {
int x, y;
A(int x, int y) : x(x), y(y) {}
};
A myfun() {
return A(0, 42); // return two values
}
or:
void myfun(int & a, int & b) {
a = 0;
b = 42;
}
No, but you can return a pair or boost::tuple which can contain multiple values.
In addition, you can use references to return multiple values like this:
void MyFunction(int a, int b, int& sum, int& difference);
You would call this function like this:
int result_sum;
int result_difference;
MyFunction(1, 2, result_sum, result_difference);
As Hogan points out, technically this isn't returning multiple variables, however it is a good substitute.
A function can return values in the specified ways:
Via return value of any type
Via a pointer
Via a reference
Via setting a global variable (highly not recommended)
If you need a self contained return value, you would typically wrap the types you need in a struct and return an object of that struct by value. If you want to avoid keeping a local copy you would pass in a reference parameter to be modified.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
int a;
int b;
}Mystruct;
Mystruct myfun();
int main()
{
char name[30];
Mystruct ms2;
ms2 = myfun();
printf("val1: %d val2: %d",ms2.a,ms2.b);
return 0;
}
Mystruct myfun()
{
int a,b;
Mystruct ms;
a = 10;
b = 20;
ms.a=a;
ms.b=b;
return(ms);
}
use structure and return multiple value with different data type.
main()
{
int a=10,b=20;
int *c;
c=aa(a,b);
printf("%d %d",*c,*c+1);
}
void aa(int a,int b)
{
int c1[2];
c1[0]=b+a;
c1[1]=a-b;
return(c1);
}
here, the address of c1 will be return. so it will store in main c cariable. we can retrive both variable via pointer,