You are not logged in.

#1 2009-04-26 23:01:58

sa
Member
From: boston ma
Registered: 2008-05-23
Posts: 127
Website

[C] avoiding global variables

i have some variables in a C program i am writing which I need to be able to use through different functions. is there any way to do this without making global variables? global variables are gross and I'd like to avoid them if I can. for instance, i have a float named "balance" which I need to ba able to use in several different functions.

Offline

#2 2009-04-26 23:28:37

jumzi
Member
Registered: 2009-02-20
Posts: 69

Re: [C] avoiding global variables

Hmm... i'm not very experinced with C (just started reading doing tutorials etc.) But shouldn't pointers do what you want?

http://crasseux.com/books/ctutorial/Poi … l#Pointers

Offline

#3 2009-04-27 02:01:23

hacosta
Member
From: Mexico
Registered: 2006-10-22
Posts: 423

Re: [C] avoiding global variables

well global variables are just a tool the language gives you and many times they do have legitimate use, so in that sense i would disagree with the gross part... that said, what's wrong with

void foo(float *balance){
   /* you can now read your balance */
}

edit: missed a *

Last edited by hacosta (2009-04-27 03:02:55)

Offline

#4 2009-04-27 02:43:28

djgera
Developer
From: Buenos Aires - Argentina
Registered: 2008-12-24
Posts: 723
Website

Re: [C] avoiding global variables

Used with some cautions, can simplify the code, instead of passing to each function. Like the most discused "goto" smile

For example, you can declare a global variable but restricted to the current source file, declaring as static. So a global variable is global, but only under the file that is declared, not in all program.

As said jumzi, you can use pointers, when you need that the function modify a valued pased in parameters.

Offline

#5 2009-04-28 04:45:16

pauldonnelly
Member
Registered: 2006-06-19
Posts: 776

Re: [C] avoiding global variables

sa wrote:

for instance, i have a float named "balance" which I need to ba able to use in several different functions.

The typical way to make a value available to a function is to pass it as a parameter. Why can't you do that?

Offline

#6 2009-04-28 18:12:46

sa
Member
From: boston ma
Registered: 2008-05-23
Posts: 127
Website

Re: [C] avoiding global variables

pauldonnelly wrote:
sa wrote:

for instance, i have a float named "balance" which I need to ba able to use in several different functions.

The typical way to make a value available to a function is to pass it as a parameter. Why can't you do that?

I'm not sure how to, I'm very new to C. I'll give it a shot when I get back on my compiuter

Offline

#7 2009-04-29 03:46:30

Varreon
Member
Registered: 2008-07-03
Posts: 95

Re: [C] avoiding global variables

void functionone(float b);
void functiontwo(float b);

int main(){
float balance;

functionone(balance);
functiontwo(balance);
return 0;
}


And of course, you declare your entire function later on. I can be more specific if you need me to, but I suggest you read up on your C.

Offline

#8 2009-04-29 05:30:16

Wra!th
Member
Registered: 2009-03-31
Posts: 342

Re: [C] avoiding global variables

#include <stdio.h>
void ye_olde_switcharoo(char *l)
{
        sprintf(l, "New string\n");
}
int main()
{
        char line[256] = "Initial string\n";
        printf(line);
        ye_olde_switcharoo(line);
        printf(line);
return 0;
}

This is obviouslly a really crappy example but you get the idea

Something more fun

#include <stdio.h>

void do_eet(char *l)
{
  while(*l) printf("%c", *l++);
}
 
int main()
{       
        char line[256] = "Initial string\n";
        do_eet(line);
        return 0;
}

And at last, a godly link: http://pweb.netcom.com/~tjensen/ptr/pointers.htm

Last edited by Wra!th (2009-04-29 05:36:19)


MacGregor DESPITE THEM!
7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00

Offline

#9 2009-04-29 11:56:49

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: [C] avoiding global variables

Varreon wrote:

void functionone(float b);
void functiontwo(float b);

This won't work if functionone and functiontwo need to update the value of balance - you have to pass it in as a pointer, like so:

void functionone(float* b);
void functiontwo(float* b);

int main(){
    float balance;
    functionone(&balance);
    functiontwo(&balance);
    return 0;
}

void functionone(float* b)
{
    (*b) = 10; // note the way you change the value of things with pointers
}
void functiontwo(float* b)
{
    (*b) = 0.1 * (*b); // note the way you change the value of things with pointers
}

Offline

#10 2009-04-29 12:36:56

alexandrite
Member
Registered: 2009-03-27
Posts: 326

Re: [C] avoiding global variables

If you don't want to use pointers, which is kind of understandable, you can just have the functions return the balance.

float foo(float b);
float bar(float b);

int main()
{
  float balalance;

  //(Do whatever you do to initialize balance)

  balance = foo(b);
  
  //etc
}

float foo(float b)
{
  b = b + 1;

  return b;
}

Whenever you call foo or bar, it will give the value you put after "return" in foo or bar to the variable after the equals sign in main.

You can only return one variable per function, but you can generally write your code cleverly enough that it isn't a problem.

Offline

#11 2009-04-29 13:44:42

halhen
Member
From: Gothenburg, Sweden
Registered: 2009-04-08
Posts: 56
Website

Re: [C] avoiding global variables

OT (assuming "balance" represents money): Floating point variables are imprecise and shouldn't be used to store data where accuracy is important. Using floats to represent money is IMO way more gross than global variables since the former only works under certain circumstances.


statnot - status text manager and notification-daemon for dwm, wmii and the like
shic - SHellscript Irc Client

Offline

#12 2009-04-29 14:07:42

alexandrite
Member
Registered: 2009-03-27
Posts: 326

Re: [C] avoiding global variables

halhen wrote:

OT (assuming "balance" represents money): Floating point variables are imprecise and shouldn't be used to store data where accuracy is important. Using floats to represent money is IMO way more gross than global variables since the former only works under certain circumstances.

If you're representing data that only has to be accurate to three or four decimal places (like dollar figures in most business accounting), a float is more than accurate enough to be used for the purpose, until you're into huge, huge numbers, and most businesses will either be too small to enter that domain, or will be divided into smaller subsections that are also to small to enter that domain.

Of course, if OT means Off-Topic, I guess neither of us should be talking about this here anyway.

Last edited by alexandrite (2009-04-29 14:08:27)

Offline

#13 2009-04-29 14:16:21

halhen
Member
From: Gothenburg, Sweden
Registered: 2009-04-08
Posts: 56
Website

Re: [C] avoiding global variables

alexandrite wrote:
halhen wrote:

OT (assuming "balance" represents money): Floating point variables are imprecise and shouldn't be used to store data where accuracy is important. Using floats to represent money is IMO way more gross than global variables since the former only works under certain circumstances.

If you're representing data that only has to be accurate to three or four decimal places (like dollar figures in most business accounting), a float is more than accurate enough to be used for the purpose, until you're into huge, huge numbers, and most businesses will either be too small to enter that domain, or will be divided into smaller subsections that are also to small to enter that domain.

Of course, if OT means Off-Topic, I guess neither of us should be talking about this here anyway.

We probably shouldn't, but it's just too much fun.

I've converted a 2 MLOC system with microtransactions from floating to fixed points decimals for money. All was well for several years when running with USD. When deployed in EUR, however, customers started loosing cents - obviously not acceptable. Reason? The 25 US cent denomination worked fine but the 20 EUR-cent coin, represented as 0.2, didn't.

So it actually IS a problem, even with reasonable numbers and few decimals.

Last edited by halhen (2009-04-29 14:18:00)


statnot - status text manager and notification-daemon for dwm, wmii and the like
shic - SHellscript Irc Client

Offline

#14 2009-04-30 00:05:50

alexandrite
Member
Registered: 2009-03-27
Posts: 326

Re: [C] avoiding global variables

halhen wrote:
alexandrite wrote:
halhen wrote:

OT (assuming "balance" represents money): Floating point variables are imprecise and shouldn't be used to store data where accuracy is important. Using floats to represent money is IMO way more gross than global variables since the former only works under certain circumstances.

If you're representing data that only has to be accurate to three or four decimal places (like dollar figures in most business accounting), a float is more than accurate enough to be used for the purpose, until you're into huge, huge numbers, and most businesses will either be too small to enter that domain, or will be divided into smaller subsections that are also to small to enter that domain.

Of course, if OT means Off-Topic, I guess neither of us should be talking about this here anyway.

We probably shouldn't, but it's just too much fun.

I've converted a 2 MLOC system with microtransactions from floating to fixed points decimals for money. All was well for several years when running with USD. When deployed in EUR, however, customers started loosing cents - obviously not acceptable. Reason? The 25 US cent denomination worked fine but the 20 EUR-cent coin, represented as 0.2, didn't.

So it actually IS a problem, even with reasonable numbers and few decimals.

Huh.  I stand corrected, it would seem.

Offline

#15 2009-04-30 01:59:47

Intruder89
Member
From: Belgrade, Serbia
Registered: 2009-02-20
Posts: 28

Re: [C] avoiding global variables

Well maybe guys already solved his problem but I would advise using retunr value if functions are one-level deep. If using recursion or 2 or more lvl deep function calls then forget return value and use pointers! You can create one variable in main and then pass its address to all others functions which arguments in that case are pointers to that type smile

Offline

#16 2009-04-30 02:48:31

Peasantoid
Member
Registered: 2009-04-26
Posts: 928
Website

Re: [C] avoiding global variables

I believe you can use "static" variables within functions? If that's the only place you're going to use the var, this could be a timesaver.

Edit: Or is that just a PHP thing...

Last edited by Peasantoid (2009-04-30 02:48:44)

Offline

#17 2009-04-30 05:22:38

pauldonnelly
Member
Registered: 2006-06-19
Posts: 776

Re: [C] avoiding global variables

Cerebral wrote:
int main(){
    float balance;
    functionone(&balance);
    functiontwo(&balance);
    return 0;
}

Why write brittle code with side-effects?

int main () {
    float balance = something;
    balance = functiontwo(function1(balance));
    return 0;
}

IMO, if you want to assign, use an equals sign. Sometimes in C you can't just return a value (for example if you have multiple values to return or you'd rather have the caller allocate memory) so you do need to modify parameters, but avoid it wherever possible.

Offline

#18 2009-04-30 09:53:22

HashBox
Member
Registered: 2009-01-22
Posts: 271

Re: [C] avoiding global variables

Peasantoid wrote:

I believe you can use "static" variables within functions? If that's the only place you're going to use the var, this could be a timesaver.

Edit: Or is that just a PHP thing...

Pretty sure that applies to C as well, so yeah.

Offline

#19 2009-05-01 21:09:29

Themaister
Member
From: Trondheim, Norway
Registered: 2008-07-21
Posts: 652
Website

Re: [C] avoiding global variables

Static types exist in C too, ye.

#include <stdio.h>

void changeBalance(int change){
   static int balance = 0;
   balance += change;
   printf("Balance is: %i", balance);
}

int main(){
   changeBalance(10);
   changeBalance(5);
   changeBalance(-20);

   return 0;
}

This outputs:
Balance is: 10
Balance is: 15
Balance is: -5

The balance value will be saved, between each function call.

IMO, if you want to assign, use an equals sign. Sometimes in C you can't just return a value (for example if you have multiple values to return or you'd rather have the caller allocate memory) so you do need to modify parameters, but avoid it wherever possible.

It's possible with structs :3 But that's messy too I guess :\

Last edited by Themaister (2009-05-01 21:13:29)

Offline

#20 2009-05-02 23:56:13

Intruder89
Member
From: Belgrade, Serbia
Registered: 2009-02-20
Posts: 28

Re: [C] avoiding global variables

With static you are creating variable that won`t be destroyed after function call and that will work BUT you don`t control destroing it, so you must use it carefull. Especialy in massive programms, creating two static variables in two diferent functions and calling it can be a runtime problem that, in massive program, is pain in the ass to find ...

OS is controling that variable (when it will be destroyed). So YES use it if must but better work on pointers smile

Offline

#21 2009-05-03 13:07:42

raf_kig
Member
Registered: 2008-11-28
Posts: 143

Re: [C] avoiding global variables

halhen wrote:

Reason? The 25 US cent denomination worked fine but the 20 EUR-cent coin, represented as 0.2, didn't.

Even though it's OT I'd like to explain that for those who don't see where the problem is coming from.

When converting between different number systems (ie base 10 to base 2) you have to
keep in mind that some numbers that have a finite representation in one system may have
an infinte representation in the other.

For example the decimal 0.2 is representend in binary as the infinite 0.00110011...  whereas converting 0.25 to binary yields 0.01

regards

raf

Last edited by raf_kig (2009-05-03 13:10:32)

Offline

Board footer

Powered by FluxBB