Home > OS >  Passing variables between functions in c with out using global variables
Passing variables between functions in c with out using global variables

Time:11-09

I am trying to print the value of a local variable inside of main, form another function with out using global variables. What would be the best way to do so .(I am using c)

#include <stdio.h>

int function1();

int main(void) {
  int hello=10;
  printf(function1());
}

int function1(int ip){
  printf("hello%d",ip); 
}

I am expecting the 10 to be printed next to the "hello" but instead get a 0.

CodePudding user response:

You need to call the function passing the value (or variable) required.

int function1(int );

int main(void) 
{
  int hello=10;
  function1(hello);
  function1(130);
}

int function1(int ip)
{
  return printf("hello - %d\n",ip); 
}

https://godbolt.org/z/97o3dPWzj

CodePudding user response:

change

int function1();

to

int function1(int);

and

 printf(function1());

to

  printf(function1(hello));
  •  Tags:  
  • c
  • Related