A few lessons ago I learned about variables, and got a question in my homework about swapping two numbers - I used a third variable to solve this question.
The solution looked somewhat like this:
#include <stdio.h>
int main(void) {
int x, y;
scanf("%d %d", &x, &y);
// swappring the values
int temp = x;
x = y;
y = temp;
printf("X is now %d and Y is now %d", x, y);
}
Now I'm learning about functions, and I wanted to try and solve the previous question with a helper swap function.
This is the code I've written:
#include <stdio.h>
void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
int main(void) {
int a = 3, b = 4;
swap(a, b);
printf("%d %d\n", a, b);
}
I don't know why, but the output is still 3 4 even though I changed the value inside the swap() function.
Why is this happening?
Pass address of x and y as arguments to function. Right now they are local variables, changes are not made to original variables .
Do as follows-
void swap(int *x,int *y){
/* dereference pointers and swap */
int temp = *x;
*x = *y;
*y = temp;
}
And call in main like this -
swap(&x,&y);
What you are doing is passing parameter by value. It means that during the function call, copies of parameters are created. So inside the function you are working on copies of actual variables.
Instead you need to pass it as a reference. Please read more about pass-by-value vs pass-by-reference.
#include <stdio.h>
void swap(int& x,int& y) //Instead of passing by value just pass by reference
{
int temp=x;
x=y;
t=yemp;
}
int main() {
int a=3,b=4;
swap(a,b);
printf("%d %d\n",a,b);
return 0;
}
EDIT:
C does not have references. Above code will work in c++ instead. To make in work in C, just use pointers and de-reference it inside the function.
Related
void noOfClients(struct noOfClients *q );
I understand that a pointer's name holds the memory address of a variable.
But, when * comes with a pointer, it represents the content of that location.
In the above line of code, when passing a by reference, we'd say:
void noOfClients( &q);
But why?
Thank you.
* has different meaning when it is used in a variable/argument declaration and when it is used as a pointer dereference operator.
In a variable/argument declaration, it declares the variable/argument to be of a pointer type.
struct noOfClients *q
declares q to be a pointer to a struct noOfClients.
When used in an expression,
*q
dereferences where q points to.
PS
void noOfClients( &q);
is not the right way to call the function. Just use:
noOfClients(&q);
That will work if q is declared as an object.
struct noOfClients q;
noOfClients(&q);
void func(foo *a);
This is a function prototype of a function taking a pointer to a foo. Some people like to write this as
void func(foo* a);
There's no difference, but you might say that the function takes a "foo-pointer", rather than a "pointer to a foo".
a is a foo*
*a is a foo
There is no difference.
because & indicates the address of a particular variable and when you deal with functions so when you pass a variable to the function so you do some changes in that variable, sometimes the reflection of value are not done in that variable but if you pass a variable with its address then reflection will be done properly just try and understand following two codes it will sure help you
without &
#include <stdio.h>
void swap(int, int);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = b;
b = a;
a = temp;
}
with &
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(&x, &y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
Is that possible to send two values to function and return both separately without using data structures such as arrays?
like this:
#include<stdio.h>
int f(int a,int b)
{
a*=2;
b*=2;
return ?????????
}
int main()
{
int x=5,y=10,k;
k=f(x,y) ?????????
printf("%d",k); ????????
}
You cannot directly return more than one item (where an item could be a structure containing multiple items within). However you can "pass by reference" if you're comfortable with pointers.
#include <stdio.h>
void f(int *a, int *b)
{
*a *= 2;
*b *= 2;
}
int main()
{
int x=5, y=10;
f(&x, &y);
printf("new x: %d, new y: %d", x, y);
}
See the results of this at http://ideone.com/p4Xiqv
No, its not possible to return more than one values without using any data structures. But, you can pass any number of arguments.
So I have to create two functions. In the int main, the program asks to input an x and y value. On the first function, it adds 1 to the x and y value. And on the next function, it prints out the result from that function. And now my problem is that the 2nd function doesn't print out the output from the first function, I do not know what I'm doing wrong, here's my code so far:
#include <stdio.h>
void plusone(int *x,int *y);
void printresult(int *x, int *y);
int main()
{
int x,y;
printf("enter x variable: ");
scanf("%d",&x);
printf("enter y variable: ");
scanf("%d",&y);
plusone(&x,&y);
printf ("%d and %d\n\n",x,y);
printresult(&x,&y);
}
void plusone(int *x,int *y)
{
return *x+1;
}
void printresult(int *x,int *y)
{
printf("the result is: x:%d y:%d",*x,*y);
}
so when I run that program, enter 1 for x and 2 for y, the output is still 1 and 2, but it's supposed to be 2 for x and 2 for y after the plusone function, can I ask what's wrong with my code? Sorry for my english but I hope I explained it well, I am new to C programming
A better answer is that the plusone function is not applying any side-effect on the *x parameter. Here is a plusone function that has a side-effect (actually two--one on each variable passed in):
void plusone(int *x,int *y)
{
*x = *x+1;
*y = *y+1;
}
You are passing a pointer to plusone - that's a good start. However, you are not using that pointer to update the value passed in:
void plusone(int *x,int *y)
{
*x = *x+1;
}
or better
void plusone(int *x,int *y)
{
(*x)++;
}
Now you assign a new value to whatever x is pointing, that is, to the variable x of main.
Note: Since you were returning a value from a function declared void, the compiler should have given you a warning.
Note: although passing by pointer to plusone is necessary, you can pass by value to printresult, because the function does not need to change values of the local variables in main that you pass to it.
void plusone(int *x,int *y)
{
return *x+1;
}
should be
void plusone(int *x,int *y)
{
(*x)++; //or *x+=1; which is the short for *x=*x+1;
}
You cannot return an int for a function that does not return anything (void).But here,I don't think you were attempting to return a variable.You wanted the variable x to be incremented once.So just do that in your program just like I've done above.
You should not return from plusone, this is the right solution
#include <stdio.h>
void plusone(int *x, int *y);
void printresult(int x, int y);
int /* main() returns int */ main()
{
int x, y;
printf("enter x variable: ");
scanf("%d",&x);
printf("enter y variable: ");
scanf("%d",&y);
plusone(&x, &y);
printresult(x, y);
return 0; // main sholud return `int' as you see from it's definition.
}
void
plusone(int *x, int *y)
{
*x += 1;
*y += 1;
}
void printresult(int x, int y)
{
printf("the result is:\n\tx: %d\n\ty: %d\n", x, y);
}
You said,
it adds 1 to the x and y value_
in your plusone function you was passing int *y but never doing anything with it, and int *x but not updating it's value.
plusone is trying to return an int what it's return type is void. And it isn't even trying to change anything (no assignment statement).
If you're trying to manipulate the x and y variables directly, like I think you are, you need to do something like
*x += 1;
*y += 1;
in that function
How about this solution.
void plusone(int *x,int *y)
{
*x += 1;
}
I think your original source will make compile error due to return int in void function
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.
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.
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]);
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
I just started learning C and I was confused about why do I have to use pointers to implement a swap function?
Version where swap does not work:
#include <stdio.h>
void swap(int i, int j) {
int t = i;
i = j;
j = t;
}
int 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);
return 0;
}
Version where swap works:
#include <stdio.h>
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);
}
By default function arguments are passed by value in C and C++. This basically means a copy of the passed argument is received in the function. This copy is distinct from the passed variable and any change on this copy is not reflected back to the passed argument.
So your first snippet actually swaps copies of the passed arguments and not the arguments themselves.
For the swapping to be reflected back to the arguments being passed, You need to pass by reference, In C this is acheived by using pointers. Where the address of the arguments is passed to function and the function actually operates on the memory address passed to it, i.e: the original variable who's value is being passed.
swap(a,b);
void swap(int i, int j) {
int t = i;
i = j;
j = t;
}
The above code fails because, the variables i and j are local to the function swap , which means the variables have their scope limited to the function swap , and their life is lost once the function terminates.
One workaround is to use pass by address as shown in the code below...
swap(&a,&b);
void swap(int* i, int* j) {
int t = *i;
i* = *j;
j* = t;
}
Now the variables i and j, are pointers to original variables a and b , which means they are acting on behalf of a and b, and hence even if the pointers have limited scope within the function, they are able to indirectly modify variables a and b.
Why have you presented two programs back to back?Those are two separate programs.The first one ,despite all its fallacies about void main() and stuff, intends to(but doesn't,as it deals with local variables) swap values by using a function that is passed copies of the integer variables a and b.This is pass-by-value.In fact, C only has pass-by-value, despite what your book by Yeshwant Kanetkar says.Anyways, to make the first program work,use the printf() to display the swapped values inside swap() function itself,as being local variables the change in values won't show in main().
void swap(int i, int j) {
int t = i;
i = j;
j = t;
printf("After. a:%d,b:%d",i,j);
}
The second program, which he may claim uses pass-by-reference, is essentially pass-by-value where copies of the addresses of the variables are passed,not the actual addresses themselves.And again, despite it's non-portable eccentricities like void main(), it does swap the values of a and b.
void swap(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
Output Before. a:23 b:47
After. a:47 b:23
I ran it on CodeBlocks.But then your author Mr.Void Main must have suggested you to use 16-bit Turbo C eh?
You can not do swap this way:
void swap(int i, int j) {
int t = i;
i = j;
j = t;
}
because i and j are passed by value. That means that it is the same as local variable tmp. Thus, modifying of the i and j does not actually modify variables that you passed, as local copies of the i and j do not exist outside the function swap().
Because of it, if you need to modify i and j from main(), you have to pass to swap() addresses of i and j of the main().
That's why the following version is actually works.
void swap(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
EDIT: In order to understand these things better, I would like to recommend you Stanford Lectures Programming Paradigms, that are available at YouTube.