Is function invocation at translation time valid? - c

I'm trying to achive a function to be called only one time. But I want to save the if (firstTime) check.
What I'm thinking about was:
while (1)
{
foo();
}
foo()
{
static int test = 1, srand (test);
test++;
}
But I couldn't find anything in the standard what is covering this.
So I'm not sure about, this is undefined. And if not so, will srand be invoked as expected? If not so, is it (as the main question is) even possible to invoke functioncalls on translationtime (what would more be, behave as if), as I'm doing here?

As an option to a first time flag, you could use a pointer to function that is initially set to the first time function, which in turn would set the pointer to function to the actual function. There's a level of indirection, but it eliminates a conditional branch.
A more general version of this idea is to use the pointer to function as a "state machine", where each function "advances" (sets) the pointer to the next state (the next function as part of a series of functions). This can be handy for event or interrupt driven code. I've used this method for device drivers and embedded code.

Your idea is probably that using a function call as an initializer for a static variable would call that function only once a program startup.
No, this is not possible in C, only constants are allowed in that context. In C++ this would be possible, and the compiler applies some secret wisdom to know in which order such initializations are effected.

Related

What is the best way to detect that a recursive function is called by another function, not by function itself?

Suppose I have a recursive function rec_fun() and it have two block of code, block_1 and block_n. block_1 must execute only once when rec_fun() is initially called by another function like main() and block_n must execute every time rec_fun() is called, whether by another function or by function itself.
rec_fun()
{
{
...
//block_1
//must be executed on first call only
...
}
{
...
//block_n
//with recursive call and exit condition
...
}
}
What is the best way to achieve this? I have thought few ways like using a counter i as parameter to rec_fun() initially passed with 0 and incrementing it in subsequent call, so that the function can determine whether it is first call or not. Another approach is to put block_n in another helper function and call it from rec_fun(). But in first approach I have to pass an unnecessary argument 0 and second approach creates an unnecessary function. What is the best way to accomplish this, according to you?
I'll appreciate if you provide some useful links to learn recursion.
Hide it behind a layer of indirection:
func()
{
//block_1
// compute what you need
// and pass it to rec_fun either as value, or as a pointer
rec_func(&block_1_result);
}
And make sure you expose only func for your users.
and second approach creates an unnecessary function
So? Unless you are in an extremely limited environment like an embedded device with very limited memory that's really not an issue. And the function is not "unnecessary". It's unnecessary if you think the user doesn't need 2 functions, but it's necessary if you think from the implementation view: it's needed by the implementation (actually it's one solution, but still the argument holds).
I will go against your intuition completely and will suggest to combine the two approaches you consider inappropriate. Because they are appropriate. I will create a recursive implementation with extra parameter, but for convenience and "hiding" I will also make a wrapper function:
void rec_func(bool init)
{
if (init) {
/* initialization logoc */
}
/* common recursive code */
rec_func(false);
}
void wrapper_func(void)
{
rec_func(true);
}
Note, nothing is "unnecessary" here. The extra parameter helps to keep the function logic in one unit. The wrapper function helps the caller not to mess with unrelated parameters.
Your second solution is usually the correct one.
The second function isn't any less necessary than any other function. You have one function that defines what is needed to implement whatever it is that the external caller expects your code to do. You have another to define whatever it is that you're going to do recursively.
Those apparently do different things and meet different requirements. As such, it's entirely appropriate that they be implemented in different functions.
It's possible to combine these into a single function that varies its behavior depending on a parameter that's passed. If the difference in behavior is small enough, this can be a somewhat reasonable approach--but I would say having one function do two different sorts of things is generally a kludge. The only question is whether it's a small enough kludge that you choose to overlook its being kludgy, or a big enough one that you shouldn't overlook it.
As so ensuring that the second function isn't accidentally called by some "outsider", the usual is to make it a static function, so you'd have a structure on this general order:
foo.h
#pragma once
int foo(int);
foo.c
typedef result_t /* whatever */;
static result_t blocka(int) {
// stuff for block a
}
static int blockb(result_t const *) {
// stuff for block b
}
int foo(int input) {
result_t internal_result = blocka(input);
return blockb(&internal_result);
}
In this case, I've written both blocka and blockb as separate "unnecessary" functions. Since I don't know what either your block a or block b does, it's hard to guess whether that's justified or not. But I would not start by thinking in terms of whether a function is necessary. Rather the opposite, for almost any block of code with a reasonably well defined interface and functionality, writing a function to embody that block of code should be more or less the default.
For example, if you have an if/then/else kind of situation:
if (foo) {
// do foo stuff
} else {
// do not-foo stuff
}
Think about/ask yourself whether you can give a meaningful name to the "do foo stuff" block and/or the "do not-foo stuff" blocks. That is, can you give a name to what they're doing?
If so, there's a reasonable chance that they should be implemented as functions, and then your if/then/else block can become a more readable, higher-level guide to what's going on:
if (data_sorted(input))
process_sorted_data(input);
else
process_random_data(input);
Moving these blocks of code into (reasonably well-named) functions makes it much easier for a reader to understand the intent behind the code, rather than having to divine your intent from the content.
The C language does not give the function any information regarding its caller so there is no portable way to test whether rec_fun() was called from another function or recursively from itself.
Your goal can be achieved by passing an extra argument to the function with a different value for outsider and recursive calls. This is cumbersome and error prone.
The standard approach for your problem is to use an ancillary function rec_fun1(): the main function rec_fun() is called from other functions and the recursive ancillary function is called from rec_fun() and recursively from rec_fun1() itself.
A classic example of this is mergesort() which would allocate the temporary work array and call a recursive mergesort1() that uses the temporary array to perform the top down merge sort algorithm. Upon return from the call to mergesort1(), mergesort() frees the temporary array and returns to the caller.
You can use static variable as counter.
rec_fun()
{
static int i = 0;
if (++i == 1) {
...
//block_1
//must be executed on first call only
...
}
{
...
//block_n
//with recursive call and exit condition
...
}
--i; // internal house keeping to track whether internal, or external caller
}
You can pass a parameter that you change as you move down the recursion and make block 1 ran based on the condition of the parameter. If you use an if/else if for block 1 and 2 then you're good.
your_func(the_param){
if(the_param) {
// the code that only runs on the first call
}
else if(the_param) {
// the code that runs every other call
}

C: Using static volatile with "getter" function and interruptions

Suppose I have the following C code:
/* clock.c */
#include "clock.h"
static volatile uint32_t clock_ticks;
uint32_t get_clock_ticks(void)
{
return clock_ticks;
}
void clock_tick(void)
{
clock_ticks++;
}
Now I am calling clock_tick (i.e.: incrementing clock_ticks variable) within an interruption, while calling get_clock_ticks() from the main() function (i.e.: outside the interruption).
My understanding is that clock_ticks should be declared as volatile as otherwise the compiler could optimize its access and make main() think the value has not changed (while it actually changed from the interruption).
I wonder if using the get_clock_ticks(void) function there, instead of accessing the variable directly form main() (i.e.: not declaring it as static) can actually force the compiler to load the variable from memory even if it was not declared as volatile.
I wonder this as someone told me this could be happening. Is it true? Under which conditions? Should I always use volatile anyway no matters if I use a "getter" function?
A getter function doesn't help in any way here over using volatile.
Assume the compiler sees you've just fetched the value two lines above and not changed it since then.
If it's a good optimizing compiler, I would expect it to see the function call has no side effect simply optimize out the function call.
If get_clock_ticks() would be external (i.e. in a separate module), matters are different (maybe that's what you remember).
Something that can change its value outside normal program flow (e.g. in an ISR), should always be declared volatile.
Don't forget that even if you currently compile the code declaring get_clock_ticks and the code using it as separate modules, perhaps one day you will use link-time or cross-module optimisation. Keep the "volatile" even though you are using a getter function - it will do no harm to the code generation in this case, and makes the code correct.
One thing you have not mentioned is the bit size of the processor. If it is not capable of reading a 32-bit value in a single operation, then your get_clock_ticks() will sometimes fail as the reads are not atomic.

Use of (apparently) empty C function

Can anyone comment on the point of the following function, which appears to do not very much:
// Returns stored values
int getDetails(const int param1[],
int* param2,
int* param3,
int* param4)
{
(void)param1;
(void)param2;
(void)param3;
(void)param4;
return 0;
}
The comment is actually there with the code. I'm thinking it must be some kind of odd stub but it is being called and I'm racking my brains to try to imagine what I'm missing.
My best hunch so far is that the function has been deprecated but not removed and the (void)param is to avoid compiler warnings about unused variables.
Statements like (void)param1; are typically used to suppress warnings about unused function parameters. (As an aside, in C++ you could also comment out or remove the parameter names.)
You're correct that the function does nothing. If other code doesn't create a pointer to it, you could safely remove it.
It's an empty function. Casts to void suppress warnings about unused parameters.
Such functions are often used when a function must be called unconditionally or a valid function pointer must be provided, but really the function has nothing to do.
I have a few such functions in my compiler's code generator. There are two code generators actually, one for x86 and the other for MIPS. I compile and link one or the other, never both at the same time.
The code generators are different internally but have the same external API. So, some functions specific to one CPU have some work to do while the same functions for the other have nothing to do. Logically, some of them are empty since there's nothing to do.
My guess (opinion - sorry!) that it could be a stub as you say. If you have a function that takes one or more function pointers to achieve something and it does not allow for a NULL (don't bother with this) then you have to provide something for it to call.
The casts are probably to avoid the "unused parameter" warning.
You're right, it has no point.
All it does is explicitly ignore the arguments by evaluating them and casting the result to (void), and return 0.
Is the return value being used in the context of the call? The best approach is of course to remove the call and replace it with a 0 if the return value is being used, and test the program.
Some Compilers shows error/warning when you are not using the arguments passed to it , to avoid that mention that like it in your code . If the function is not called any where or not assigned to any function pointers , you can remove it as it is not doing anything specific

using static keyword in C local scope to function

Is there any difference in these two? If so, what exactly is the difference? Assume they are in a C function that may be called multiple times.
declare and assign in same statement
static uint32_t value = x; // x varies and may be passed into function.
declare in one statement and assign in next statment.
static uint32_t value;
value = x; // x varies;
Is value updated only the first time it is declared/initialized or even on subsequent calls.
My understanding of (1) is that it is only set the first time that line is executed so even if x changes the next time the line executes, value will remain the same. I am not sure about (2) but clarification on both will be very helpful
EDIT: Compiler ARM(ADS1.20).
EDIT: A follow up question on (2) from the answers given so far. Is the declaration(not the assignment) repeated on every call or just the first time?
The first should not compile; the static variable requires a constant initializer.
The second sets value each time the function is called, so there was no need to make it static in the first place.
If the first notation was correct - initialized value to 1, say - then it would be initialized once when the program starts and would thereafter only take new values when the code changed it. The second notation still sets value on each call to the function, and so renders the use of static pointless. (Well, if you try hard enough, you can devise scenarios under which the second version has a use for static. For example, if the function returns a pointer to it that other code then modifies, then it might be needed, but that is esoteric in the extreme and would be a pretty bad 'code smell'.)
1 is only executed once, but for 2 value will be reassigned every time.
Static variables are initialized only once.
These are very different declarations.
The first one is declaring a static local variable and giving it an initial value (this should not actually compile given that x is not a constant). This will only occur once before the function is every executed. This is almost certainly the initialization you want.
The second declaration is updating the value every time the function is called. If you want the variable to always start the function with the same value this is the right approach. But if this is truly what you want, then why use a static at all? Just use a local variable.
Your intuition is right. In the second example value is set to x each time the method is called. Static variables need to be initialized and declared in one statement if you only want it to run once.
If you always want value to have the value x, don't declare it as static.
When compiled, the first one will be put into the ".data" section, where data is initialized, while the second one will be put into the ".bss" section, where data is uninitialized.
Use readelf -S xx.o can check the section size of compiled object file.
example 1:
static int i;
void test(){
i = 2;
}
example 2:
static int i=1;
void test(){
i = 2;
}
Folks - In C, the first declaration is perfectly legal. It will compile, and could be used to initialize the value. You could combine the line of code from the second declaration to ensure it gets updated every subsequent function execution. This is commonly used, in particular in embedded programs where memory and resources are more scarce than computers or distributed applications.
The reason why you would use a static is to ensure the variable has a data lifecyle that continues throughout program execution while limiting its access to only the function the static is declared, or any function in the file if the static declaration is on top of the file, otherwise, the data will be lost every time the function is exited. This is good programming practice to avoid inadvertent access to data objects that must be secured and restricted. That comment only applies to the C programming language, don't mistake this to apply for C++ (where it does in some instances), or JAVA. Static in Java has a completely different meaning. From what I've read in this thread, few seem to understand how the keyword static works in C, and are confusing the keyword static form other languages to apply in C. In C, static is a very important keyword that helps manage function and data access, and you can initialize a static variable with another variable provided it is within scope, and you can update that value throughout program execution, which would probably what you need to do anyways.

Internal static variables in C, would you use them?

In C you can have external static variables that are viewable every where in the file, while internal static variables are only visible in the function but is persistent
For example:
#include <stdio.h>
void foo_bar( void )
{
static counter = 0;
printf("counter is %d\n", counter);
counter++;
}
int main( void )
{
foo_bar();
foo_bar();
foo_bar();
return 0;
}
the output will be
counter is 0
counter is 1
counter is 2
My question is why would you use an internal static variable? If you don't want your static variable visible in the rest of the file shouldn't the function really be in its own file then?
This confusion usually comes about because the static keyword serves two purposes.
When used at file level, it controls the visibility of its object outside the compilation unit, not the duration of the object (visibility and duration are layman's terms I use during educational sessions, the ISO standard uses different terms which you may want to learn eventually, but I've found they confuse most beginning students).
Objects created at file level already have their duration decided by virtue of the fact that they're at file level. The static keyword then just makes them invisible to the linker.
When used inside functions, it controls duration, not visibility. Visibility is already decided since it's inside the function - it can't be seen outside the function. The static keyword in this case, causes the object to be created at the same time as file level objects.
Note that, technically, a function level static may not necessarily come into existence until the function is first called (and that may make sense for C++ with its constructors) but every C implementation I've ever used creates its function level statics at the same time as file level objects.
Also, whilst I'm using the word "object", I don't mean it in the sense of C++ objects (since this is a C question). It's just because static can apply to variables or functions at file level and I need an all-encompassing word to describe that.
Function level statics are still used quite a bit - they can cause trouble in multi-threaded programs if that's not catered for but, provided you know what you're doing (or you're not threading), they're the best way to preserve state across multiple function calls while still providing for encapsulation.
Even with threading, there are tricks you can do in the function (such as allocation of thread specific data within the function) to make it workable without exposing the function internals unnecessarily.
The only other choices I can think of are global variables and passing a "state variable" to the function each time.
In both these cases, you expose the inner workings of the function to its clients and make the function dependent on the good behavior of the client (always a risky assumption).
They are used to implement tools like strtok, and they cause problems with reentrancy...
Think carefully before fooling around with this tool, but there are times when they are appropriate.
For example, in C++, it is used as one way to get singleton istances
SingletonObject& getInstance()
{
static SingletonObject o;
return o;
}
which is used to solve the initialization order problem (although it's not thread-safe).
Ad "shouldn't the function be in its own file"
Certainly not, that's nonsense. Much of the point of programming languages is to facilitate isolation and therefore reuse of code (local variables, procedures, structures etc. all do that) and this is just another way to do that.
BTW, as others pointed out, almost every argument against global variables applies to static variables too, because they are in fact globals. But there are many cases when it's ok to use globals, and people do.
I find it handy for one-time, delayed, initialization:
int GetMagic()
{
static int magicV= -1;
if(-1 == magicV)
{
//do expensive, one-time initialization
magicV = {something here}
}
return magicV;
}
As others have said, this isn't thread-safe during it's very first invocation, but sometimes you can get away with it :)
I think that people generally stay away from internal static variables. I know strtok() uses one, or something like it, and because of that is probably the most hated function in the C library.
Other languages like C# don't even support it. I think the idea used to be that it was there to provide some semblance of encapsulation (if you can call it that) before the time of OO languages.
Probably not terribly useful in C, but they are used in C++ to guarantee the initialisation of namespace scoped statics. In both C and C++ there are problemns with their use in multi-threaded applications.
I wouldn't want the existence of a static variable to force me to put the function into its own file. What if I have a number of similar functions, each with their own static counter, that I wanted to put into one file? There are enough decisions we have to make about where to put things, without needing one more constraint.
Some use cases for static variables:
you can use it for counters and you won't pollute the global namespace.
you can protect variables using a function that gets the value as a pointer and returns the internal static. This whay you can control how the value is assigned. (use NULL when you just want to get the value)
I've never heard this specific construct termed "internal static variable." A fitting label, I suppose.
Like any construct, it has to be used knowledgeably and responsibly. You must know the ramifications of using the construct.
It keeps the variable declared at the most local scope without having to create a separate file for the function. It also prevents global variable declaration.
For example -
char *GetTempFileName()
{
static int i;
char *fileName = new char[1024];
memset(fileName, 0x00, sizeof(char) * 1024);
sprintf(fileName, "Temp%.05d.tmp\n", ++i);
return fileName;
}
VB.NET supports the same construct.
Public Function GetTempFileName() As String
Static i As Integer = 0
i += 1
Return String.Format("Temp{0}", i.ToString("00000"))
End Function
One ramification of this is that these functions are not reentrant nor thread safe.
Not anymore. I've seen or heard the results of function local static variables in multithreaded land, and it isn't pretty.
In writing code for a microcontroller I would use a local static variable to hold the value of a sub-state for a particular function. For instance if I had an I2C handler that was called every time main() ran then it would have its own internal state held in a static local variable. Then every time it was called it would check what state it was in and process I/O accordingly (push bits onto output pins, pull up a line, etc).
All statics are persistent and unprotected from simultaneous access, much like globals, and for that reason must be used with caution and prudence. However, there are certainly times when they come in handy, and they don't necessarily merit being in their own file.
I've used one in a fatal error logging function that gets patched to my target's error interrupt vectors, eg. div-by-zero. When this function gets called, interrupts are disabled, so threading is a non-issue. But re-entrancy could still happen if I caused a new error while in the process of logging the first error, like if the error string formatter broke. In that case, I'd have to take more drastic action.
void errorLog(...)
{
static int reentrant = 0;
if(reentrant)
{
// We somehow caused an error while logging a previous error.
// Bail out immediately!
hardwareReset();
}
// Leave ourselves a breadcrumb so we know we're already logging.
reentrant = 1;
// Format the error and put it in the log.
....
// Error successfully logged, time to reset.
hardwareReset();
}
This approach is checking against a very unlikely event, and it's only safe because interrupts are disabled. However, on an embedded target, the rule is "never hang." This approach guarantees (within reason) that the hardware eventually gets reset, one way or the other.
A simple use for this is that a function can know how many times it has been called.

Resources