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

Edited 3 Years Ago by mike_2000_17: Fixed formatting

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;
}

Edited 6 Years Ago by creeps: n/a

This article has been dead for over six months. Start a new discussion instead.