7

With regard to memory allocation, how (or where) should I declare the following...

 2 years ago
source link: https://www.codesd.com/item/with-regard-to-memory-allocation-how-or-where-should-i-declare-the-following-variables.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

With regard to memory allocation, how (or where) should I declare the following variables?

advertisements

This question already has an answer here:

  • Are global variables bad? [closed] 28 answers

I'm not sure whether it's appropriate to ask this here. I'm concerned about the memory allocation and I don't know where to read up on that.

I'm debating with myself whether I should declare local variables per root-finding function, or just use global variables that each function can reuse per call. Please note that I don't plan on using recursion here. Just (do-)while (or for) loops only.

I'd really appreciate it if I can get sufficient explanation too.

// [1]
// global(?) variables
// functions.cpp

#include <cmath>
#include "functions.h"

using namespace std;

double guess1;     // upper
double guess2;     // lower
double root;
double prevGuess;
double sigFigs;
double minSigFigs;

double newt_rhap(params)
{
   // do stuff
}
double bisection(params)
{
   // do stuff
}

===============

// [2]
// local variables
// functions.cpp

#include <cmath>
#include "functions.h"

using namespace std;

double newt_rhap(x,y,z,f(),f_prime())
{
   double guess = x;
   double sigFigs = y;
   double minSigFigs = z;

   // do stuff
}
double false_position(w,x,y,z,a())
{
   double xr;
   double upper = w;
   double lower = x;
   double xprev;
   double fxr;
   double fxu;
   double fxl;
   double sigFigs = y;
   double minSigFigs = z;

   // do stuff
}


You should use globals when you want to share the value of variables between several functions and want to avoid passing the values inbetween the functions.

In other cases it is better to use local variables. With globals you need to be sure the value wasn't modified accidently somewhere.

Additionally, you might have to frequently reintialize the values before usage.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK