CloudN9ne
CloudN9ne

Reputation: 235

Changing values in a local scope

Does anyone know of a way I can change the values of variables that are defined locally?

#include <stdio.h>

int change(int x, int y);

int main()
{
    int x = 10;
    int y = 20;

    change(x,y);
    printf("x:%d y:%d\n", x, y);
}

int change(int x, int y)
{
    x = 20;
    y = 30;

    return(x);
    return(y);
}

I want x and y to print 20 and 30 in main(). I tried returning the values, but that didn't work. Is there another method I might be able to use? I was thinking pointers, but I don't know where to begin.

Upvotes: 0

Views: 62

Answers (3)

GmSkyStar
GmSkyStar

Reputation: 1

yes it's very easy just pass the parameters by reference to the change function so instead of int change(int x, int y) > int change(int& x, int& y) and it will works fine

Upvotes: 0

MeNa
MeNa

Reputation: 1487

Some options:

1) Pass by refernce: int change(int &x, int &y);

2) Return an array and change current values:

int* temp = new int[2];
temp[0]=x+10;
temp[1]=y+10;
return temp;

3) Return to printf directly:

printf("x:%d y:%d\n", change(x,y)[0], change(x,y)[1]);

Upvotes: 0

ouah
ouah

Reputation: 145919

Use pointers:

void change(int *x, int *y)
{
    *x = 20;
    *y = 30;
}

and call the function like: change(&x, &y); For readability you may want to use different names than x and y for the change parameters as they are not of the same type as the x and y variables declared in main.

Upvotes: 4

Related Questions