Hi, does anyone know how to pass variables between functions in C so one function can recognise the variable passed from another function.

one function knowing from another function like

length = 0;
while (length <= 5)
    {
        length ++;

    } 
    return(length);

getting the value of the length from the top to count in the bottom

for (counter = 0; counter <= length;counter += 2)
    {

        printf("hey");      
    }

these are two different functions and there is also void main

help would be appreciated

Recommended Answers

All 2 Replies

There are three ways you can do this. The first one (and the not-so-basic one) is making use of pointers. You can declare the cross-function variables inside main, and pass their addresses to the other functions, which, in turn, will modify the initial variables. Here's a sample, but unless you understand pointers, you won't make much of it:

#include <stdio.h>

void double_it(int *);

int main(void) { /* Please define main as int instead of void */

    /* I'm declaring and initializing i */
    int i = 2;

    /* I'm calling the double_it function, passing it the address of i instead of its value */
    double_it(&i);

    /* I'm now printing the variable. It should be 12 */
    printf("i: %d\n", i);

    return 0;
}

/* Definition of double_it */
void double_it(int *n) {

    /* Notice the use of pointers instead of normal variables */
    *n = *n * 2;
}

Perhaps the easiest way to do it would be to declare the cross-function variables as global (outside of main ). This way, when a function alters the variable declared as global, the actual value is changed.

#include <stdio.h>

int n;

void double_it(void);

int main(void) {

    /* Call double_it, changing the value of n */
    double_it();

    printf("n: %d\n", n);

    return 0;
}

void double_it(void) {

    n *= 2;
}

Last but not least, you can always return the modified value and reassign it.

#include <stdio.h>

int double_it(int );

int main(void) {

    int n;

    n = double_it(n);

    printf("n: %d\n", n);

    return 0;
}

int double_it(int i) {

    return i * 2;
}
#include <stdio.h>

/* function declaration */

void swap(int *x, int *y);

int main () 
{

   /* local variable definition */
   int a = 100;
   int b = 200;

   printf("Before swap, value of a : %d\n", a );

   printf("Before swap, value of b : %d\n", b );

   /* calling a function to swap the values.
    * &a indicates pointer to a ie. address of variable a and 
  * &b indicates pointer to b ie. address of variable b.
   */
   swap(&a, &b);

   printf("After swap, value of a : %d\n", a );

   printf("After swap, value of b : %d\n", b );

   return 0;
   }
commented: 8 years late. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.