-3

I am working on code where I have declared global variables at the top of the c code. Then in the main function I use random to set random values to these variables. Then the code calls upon an external function to do math on these values. However in this function all the variables appear as zero. is there a way to pass these variables?

Pseudo Code(but how code is set up)

// Header
int A, B;
main() {
    A = (rand() % 14000);
    B = (rand() % 14000);
    // other things
    math_func Printf("%d %d", A, B);
    Return
}

math_func() {
    A + B;
    A* B;
    A / B;
}

as it stands now A and B seem to 0 in math_func... any thoughts are appreciated.

NetVipeC
  • 4,402
  • 1
  • 17
  • 19
Kydos Red
  • 23
  • 4
  • 5
    Could you post a real compilable test code? – ouah Aug 07 '14 at 23:17
  • You may find this question helpful http://stackoverflow.com/questions/1433204/how-do-i-share-a-variable-between-source-files-in-c-with-extern-but-how – mathematician1975 Aug 07 '14 at 23:21
  • Pseudo-code is not useful. The error, whatever it is, is in your actual compilable code. Show us that. – Keith Thompson Aug 07 '14 at 23:24
  • 1
    Pointing out errors in your pseudocode is pointless, because you can just claim your real code does not have those problems, so please post the real code that illustrates the problem you are observing. – jxh Aug 07 '14 at 23:24
  • You've accepted an answer, so apparently you've solved your problem, whatever it was. But this question isn't going to be useful to future readers unless you update it to show your actual code. We still don't know for sure what your problem was. – Keith Thompson Aug 07 '14 at 23:50

2 Answers2

0
math_func() {
    A+B;
    A*B;
    A/B;
}

These 3 statements has no effect. For example, what do you want to achieve with this code?

A+B;

This expression leave A unchanged. You want to change A value? If so, you should use A = A+B; or A += B;. Same with other two statements. Use +=, *= and /= operators.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

This is pure speculation, but it seems that you are expecting the printf to somehow print the results of the statements inside your math_func().

If you want the results of those statements to be visible inside main(), then you will have to assign those to some variables and print out the variables in main().

#include <stdio.h>
#include <stdlib.h>


int A, B;
int C, D, E;
void math_func();
main() {
    A = (rand() % 14000);
    B = (rand() % 14000);
    // other things
    printf("%d %d\n", A, B);
    math_func();
    printf("%d %d %d\n", C, D, E);
}

void math_func() {
    C = A + B;
    D = A* B;
    E = A / B;
}

Alternately, if you want to prove to yourself that A and B are not zero inside the function, then just put a print statement inside.

void math_func() {
    printf("%d %d\n", A, B);
    C = A + B;
    D = A* B;
    E = A / B;
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329