Sumit Kumar Jha
Sumit Kumar Jha

Reputation: 1

I'm not getting the output, I was assuming

# include <stdio.h>
void fun ( int, int )  ;
int main( )
{
  int i = 5, j = 2 ;
  fun ( i, j ) ;
  printf ( "%d %d\n", i, j ) ;
  return 0 ;
}
void fun ( int i, int j )
{
 i = i * i ;
 j = j * j ;
}

Program written in C. In the output my compiler is giving me 5 2 but it was suppose to give me 25 4 What's wrong in this code?Why is this giving 5 2 as an output?

Upvotes: 0

Views: 320

Answers (2)

Joao Soares
Joao Soares

Reputation: 81

You are passing your variables by value (which means that you passing a copy of your variable, not the variable itself). Therefore when you do the calculations in the fun functions, you are not actually changing the variables, just changing the copy that you made of them. What you COULD do is pass these values by reference, however C does not have references, therefore, you should make use of pointers:

void fun ( int *i, int *j )
{
   *i = (*i) * (*i); // You should put the stars before the variables in order to deference it
   *j = (*j) * (*j);
}

And when you call the function, you should pass the parameters like this:

fun(&i, &j);

Upvotes: 0

As AKX said in the comment,

i and j are passed into fun by value, not by reference. Modifying them within fun will not modify them outside fun

To modify a variable inside a function, you'll have to pass a pointer to it. So your final code may look like this:

# include <stdio.h>
void fun ( int*, int* )  ;
int main( )
{
  int i = 5, j = 2 ;
  fun (&i,&j) ;
  printf ( "%d %d\n", i, j ) ;
  return 0 ;
}
void fun ( int* i, int* j )
{
 *i = (*i) * (*i) ;
 *j = (*j) * (*j) ;
}

Upvotes: 2

Related Questions