-2

In this code main() doesn't recognize the variable results of a called function, in this case pro_afai.

#include <stdio.h>

here i create the function pro_afai

int pro_afai(int x,int y){
int pro,afai;
pro=x+y;
afai=x-y;}

main(){

Here i tried to declare pro=0 and afai=0 into main but it still doesn't work because it prints 0,0. printf doesn't take the result from the function.

int i,j;
int pro,afai;
printf("2 num:");
scanf("%d %d",&i,&j);
pro_afai(i,j);
printf("\npro=%d\nafai=%d",pro,afai);})

but printf won't print the normal result. how can i fix it??

Eleftheria
  • 13
  • 1
  • 4
  • 2
    Please Google call by reference and call by value. – Gangadhar Sep 23 '13 at 12:31
  • possible duplicate of [How does call by value and call by reference work in C?](http://stackoverflow.com/questions/1659302/how-does-call-by-value-and-call-by-reference-work-in-c) – jev Sep 23 '13 at 12:34
  • This doesn't seem to be a pass-by-reference vs pass-by-value issue, it seems more like a not-understanding-variable-scope issue. – Dennis Meng Dec 04 '13 at 07:38
  • 1
    This question appears to be off-topic because it shows minimal research – abligh Mar 01 '14 at 18:21

1 Answers1

3

You need to pass pointers to pro and afai to your pro_afai function:

int pro_afai(int* pro, int* afai, int x,int y){
  *pro=x+y;
  *afai=x-y;
}

int main()
{
  int i,j;
  int pro,afai;
  printf("2 num:");
  scanf("%d %d",&i,&j);
  pro_afai(&pro, &afai, i,j);
  printf("\npro=%d\nafai=%d",pro,afai);
  return 0;
}

In your existing code, there were two completely independent pairs of variables pro and afai: one pair in pro_afai function and second in main. You need to pass the existing pair from main to pro_afai to make changes on it, and you can do that by passing pointers to that variables into the pro_afai function.

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91