c - Initializing a static variable in a function to a non-constant value -


I have a function that requires some continuous data, but call the function to get continuous data It is necessary that a linear search receives the statistics. I do not want to search for every call of the function, so I tried to make the static variable in question but the static variable can not be started for non-static values: < Pre class = "lang-c prettyprint-override"> int my_function (int foo) {static contact thing * bar = thing_from_name ("bar"); Return do_thing (foo, bar); }

The GCC complains correctly that "the initial element is not stable".

After considering my situation for a moment, I eat my cake and eat it too:

 > int my_function Int foo) {static constant thing = bar = null; If (! Bar) bar = item_from_name ("bar"); Return do_thing (foo, bar); }   

It still works fine, but it seems that ... is wrong. Is there any disadvantage for this approach? Is there a better way to solve my problem?

To be clear, thing_from_name is effectively a pure function, it only reads from continuous data in memory as it searches for the string, so for me one There is not really an easy way to customize continuous expression (as far as I know).

Edit: Here is a thick outline of thing_from_name for further reference:

  const thing * thing_from_name (const char * name) {const thing * t; (T = & amp; Object_Ray [0]; T-> Name! = Faucet; T ++) {If (SRCMP (T-> Name, Name) == 0) {Return T; }} Return tap; }   

For plain C, you probably have to use something similar if the Thing_from_name () is fully expressed as a static code, which can be pre-computed on time compilation, you can succeed. If not, you should use your solution, but remember that this thread is not secure-safe.

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -