Go Down

Topic: Approach to computing a value once in a library? (Read 293 times) previous topic - next topic

memotick

I'll try to describe this the best I can...

Let's say my sketch has a constant "foo=100" and I have a library called "libby" with a function called "funk".  Inside of funk there is a variable "boo" that will *always* be foo/2.  My question is, what is the approach that would allow the computation to happen only once even though funk is called many times in the sketch.

For example, is this a valid approach?
Code: [Select]

Sketch:
#include <libby.h>
const byte foo=100;
libbyClass libbyObject;
setup(){}
loop(){
libbyObject.funk(foo);
}

libby.cpp:
#include "libby.h"
libbyClass::libbyClass(){}

void libbyClass::funk(byte var){
static byte boo=var/2;
}

libby.h:
#ifndef libby_H
#define libby_H
#include "Arduino.h"

class libbyClass{

public:
  libbyClass();
  void funk(byte var);

};
# endif


Thanks!

PeterH

I'd have the sketch pass in the value through a constructor or configuration method, and design the sketch so that the value was only passed on once. In your example, calling funk() repeatedly from loop() doesn't make sense; it would be better called once from setup(), or pass the value in via a constructor argument.
I only provide help via the forum - please do not contact me for private consultancy.

memotick


I'd have the sketch pass in the value through a constructor or configuration method, and design the sketch so that the value was only passed on once. In your example, calling funk() repeatedly from loop() doesn't make sense; it would be better called once from setup(), or pass the value in via a constructor argument.


I think I understand how to make the computation in the constructor, however I am not at all clear how I should declare the variable "boo" in the libby.cpp and libb.h if I take that approach.  Could you provide some guidance?

Thanks

Nick Gammon

Like this:

Code: [Select]


class libbyClass
{
private:
 const byte boo;
 
public:
 // constructor
 libbyClass(const byte fubar) : boo (fubar / 2) { }
 
 // some method
 void funk();

};

void libbyClass::funk()
 {
 Serial.println (boo);
 }

const byte foo=100;
libbyClass libbyObject (foo);

void setup ()
 {
 Serial.begin (115200);
 libbyObject.funk ();
 }  // end of setup

void loop ()  { }
 
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

Go Up