small advice

May 22, 2011 at 8:57pm
hey guys!

-i have declared a variable called total inside of main
-i want to use total inside of the functions prototypes that are before main

is that possible ?


i tried it and it gives me error

total' : undeclared identifier


any advice?
May 22, 2011 at 9:07pm
You could pass the variable by to the other functions as an argument. Then they could get at its value.

If they also needed to change it then you could pass them by reference.
http://cplusplus.com/doc/tutorial/functions2/

But you can't do it how you suggest. The variable is only in scope inside the main function.
May 22, 2011 at 9:11pm
oh ok thank you very much :)
May 22, 2011 at 9:14pm
you need a forward declaration like on Line 3

or you can move the definition like Line 6 farther up

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

extern int total;
int add_one() { return ++total; }

int total = 0; 

int main(void)
{
  printf( "%d\n", add_one() );
  return 0;
}
May 22, 2011 at 9:17pm
OP said his variable was inside main. I believe use of global variables is recommended against where possible.
Topic archived. No new replies allowed.