exchange of control between functions in C language - c

Considering the following scenario:
fn(1) calls fn(2) , then
fn(2) calls fn(3), and now
fn(3) should pass the control to fn(1) instead of fn(2) and control must not come back again.
Regarding this I have tried with goto, but goto does not work between functions, its only a local jump.
I wanted to check if there is any other method I could use to send the control to another function
NOTE: NO global variable, pointer to functions will work in this case, as per my exploration

Well, the typical way of doing this would be:
int fn3() {
return 1;
}
void fn2() {
if (fn3())
return;
...
}
Not sure if you're looking for something more esoteric, such as setjmp/longjmp

You can use longjmp as a "long range goto" if you absolutely must do this.

int fn1(void) {
printf("in fn1 before calling fn2\n");
fn2();
printf("in fn1 after calling fn2\n");
return 0;
}
int fn2(void) {
printf("in fn2 before calling fn3\n");
if (1) {
return fn3();
}
printf("in fn2 after calling fn3\n");
return 0;
}
int fn3(void) {
printf("in fn3\n");
return 0;
}

You can use setjmp and longjmp to do this -- but it's almost certainly a really bad idea to actually do so. Former Fortran programmers (among others) still sometimes have nightmares about the kind of mess you seem intent on creating. Given a time when a mainframe that served 300+ simultaneous users ran at 20 MHz or so, there was some excuse at the time, even if keeping track of things was a mess. Given current computers, I question not only the utility but the very sanity of having a function call that doesn't return (especially since CPUs are now optimized for that case, so what you're asking for will be slower than normal returns).

What you try to implement are so called coroutines. While C doesn't directly support them, there are ways to exploit some ingenious hacks like Duff's Device to implement them.
Simon Tatham wrote an excellent article about Coroutines in C: http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html

I think you should use setjmp() and longjmp(). The man is available here.
The following example shows you how to use it (from http://en.wikipedia.org/wiki/Setjmp.h#Example_usage ):
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main\n"); // prints
}
return 0;
}
Output :
second
main

Related

Try-catch-like Behaviour with Skipping Critical Code in C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
ANSI C equivalent of try/catch?
Is there a way to skip critical code ? More or less like try-catch in modern programming languages. Just now I'm using this technique to spot errors:
bindSignals();
{
signal(SIGFPE, sigint_handler);
// ...
}
int main(void)
{
bindsignals();
int a = 1 / 0; // division by zero, I want to skip it
return 0;
}
The problem is if I don't exit the program in the handler I get the very same error again and again. If possible I would like to avoid goto. I also heard about "longjump" or something. Is it worth to (learn to) use ?
Well, you can probably accomplish something like that using longjmp(), yes.
Possibly with the "help" of some macros. Note the comment on the manual page, though:
longjmp() and siglongjmp() make programs hard to understand and maintain. If possible an alternative should be used.
I'll throw my two cents in on this. C does not have a mechanism like the try/catch that other languages support. You can build something using setjmp() and longjmp() that will be similar, but nothing exactly the same.
Here's a link showing a nice way of using setjmp and longjmp to do what you were thinking; and a code snippet from the same source:
jmp_buf jumper;
int SomeFunction(int a, int b)
{
if (b == 0) // can't divide by 0
longjmp(jumper, -3);
return a / b;
}
void main(void)
{
if (setjmp(jumper) == 0)
{
int Result = SomeFunction(7, 0);
// continue working with Result
}
else
printf("an error occured\n");
}
I'm currently going from C to Java and I'm having a hard time understanding why you'd use try/catch in the first place. With good error checking you should be fine, always always always use the values that are returned from functions, check the errono values, and validate any user input.
I'm done. That's how my code looks like now. Almost like Java and C#.
#include <setjmp.h>
jmp_buf jumper;
#define try if (setjmp(jumper) == 0)
#define catch else
#define skip_to_catch longjmp(jumper, 0)
static void sigint_handler(int sig)
{
skip_to_catch;
}
int main(void)
{
// init error handling once at the beginning
signal(SIGFPE, sigint_handler);
try
{
int a = 1 / 0;
}
catch
{
printf("hello error\n");
}
return 0;
}

Arduino EthernetServer read() only works when Serial is initialized and read characters are printed

I have an Arduino project where I read data from a webserver.
I have an EthernetClient that reads the data character by character in a callback function.
My working code looks like (only the relevant parts):
void setup() {
Serial.begin(9600);
...
}
void loop() {
char* processedData = processData(callback); // this is in a external lib
}
boolean callback(char* buffer, int& i) {
...
if (Client.available()) {
char c = client.read();
buffer[i++] = c;
Serial.print(c);
}
...
}
This works without any problems (reading and processing the data), but when I remove Serial.begin(9600); and Serial.print(c); it stops working and I don't know why? The only thing changed is that the char c is not printed. What could be the problem?
A common reason why callback functions change their behavior when seemingly unrelated code is altered, is optimizer-related bugs.
Many embedded compilers fail to understand that a callback function (or an interrupt service routine) will ever be called in the program. They see no explicit call to that function and then assumes it is never called.
When the compiler has made such an assumption, it will optimize variables that are changed by the callback function, because it fails to see that the variable is changed by the program, between the point of initialization and the point of access.
// Bad practice example:
int x;
void main (void)
{
x=5;
...
if(x == 0) /* this whole if statement will get optimized away,
the compiler assumes that x has never been changed. */
{
do_stuff();
}
}
void callback (void)
{
x = 0;
}
When this bug strikes, it is nearly impossible to find, it can cause any kind of weird symptoms.
The solution is to always declare all file scope ("global") variables shared between main() and an interrupt/callback/thread as volatile. This makes it impossible for the compiler to make incorrect optimizer assumptions.
(Please note that the volatile keyword cannot be used to achieve synchronization nor does it guarantee any memory barriers. This answer is not in the slightest related to such issues!)
A guess: Because without the serial driver started, there is no data to process, and therefore your callback is not hit.
What were you hoping the serial callback to be doing in the absence of data?
Providing more information about Client and processData may help.

How to Pass Simple, Anonymous Functions as Parameters in C

I'm sure some variation of this question has been asked before but all other, similar questions on SO seem to be much more complex, involving passing arrays and other forms of data. My scenario is much simpler so I hope there is a simple/elegant solution.
Is there a way that I can create an anonymous function, or pass a line of code as a function pointer to another function?
In my case, I have a series of diverse operations. Before and after each line of code, there are tasks I want to accomplish, that never change. Instead of duplicating the beginning code and ending code, I'd like to write a function that takes a function pointer as a parameter and executes all of the code in the necessary order.
My problem is that it's not worth defining 30 functions for each operation since they are each one line of code. If I can't create an anonymous function, is there a way that I can simplify my C code?
If my request isn't entirely clear. Here's a bit of pseudo-code for clarification. My code is much more meaningful than this but the code below gets the point accross.
void Tests()
{
//Step #1
printf("This is the beginning, always constant.");
something_unique = a_var * 42; //This is the line I'd like to pass as an anon-function.
printf("End code, never changes");
a_var++;
//Step #2
printf("This is the beginning, always constant.");
a_diff_var = "arbitrary"; //This is the line I'd like to pass as an anon-function.
printf("End code, never changes");
a_var++;
...
...
//Step #30
printf("This is the beginning, always constant.");
var_30 = "Yup, still executing the same code around a different operation. Would be nice to refactor..."; //This is the line I'd like to pass as an anon-function.
printf("End code, never changes");
a_var++;
}
Not in the traditional sense of anonymous functions, but you can macro it:
#define do_something(blah) {\
printf("This is the beginning, always constant.");\
blah;\
printf("End code, never changes");\
a_var++;\
}
Then it becomes
do_something(something_unique = a_var * 42)
No, you cannot. Anonymous functions are only available in functional languages (and languages with functional subsets), and as we all know, c is dysfunctional ;^)
In C and pre-0x C++, no.
In C++0x, yes, using lambda functions.
The best way to simplify your code would probably to put a for loop around a switch statement.
int a_var;
for ( a_var = 0; a_var <= 30; a_var++ )
{
starteroperations();
switch (a_var)
{
case 0:
operation0(); break;
case ...:
operationx(); break;
case 30:
...
}
closingoperations();
}
If you can use Clang, you can take advantage of blocks. To learn blocks, you can use Apple's documentation, Clang's block language specification and implementation notes, and Apple's proposal to the ISO C working group to add blocks to the standard C language, as well as a ton of blog posts.
Using blocks, you could write:
/* Block variables are declared like function pointers
* but use ^ ("block pointer") instead of * ("normal pointer"). */
void (^before)(void) = void ^(void) { puts("before"); };
/* Blocks infer the return type, so you don't need to declare it
* in the block definition. */
void (^after)(void) = ^(void) { puts("after"); };
/* The default arguments are assumed to be void, so you could even
* just define after as
*
* ^{ puts("after"); };
*/
before();
foo = bar + baz*kablooie;
after();
This example gives the anonymous blocks names by assigning to a block variable. You can also define and call a block directly:
^{ puts("!"); } ();
/*| definition | invocation of anonymous function |*/
This also makes defining "struct-objects" (OOP in C using structs) very simple.
Both Clang and GCC support inner/nested functions as an extension to standard C. This would let you define the function immediately before taking its address, which might be an alternative if your control flow structure allows it: inner function pointers cannot be allowed to escape from their immediate scope. As the docs say:
If you try to call the nested function through its address after the containing function has exited, all hell will break loose. If you try to call it after a containing scope level has exited, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it's not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.
Using nested functions, you could write:
/* Nested functions are defined just like normal functions.
* The difference is that they are not defined at "file scope"
* but instead are defined inside another function. */
void before(void) { puts("before"); };
void after(void) { puts("after"); };
before();
foo = bar + baz*kablooie;
after();
Either you go the case way suggested by #dcpomero, or you do the following:
typedef void job(int);
job test1; void test1(int a_var) { something_unique = a_var * 42; }
job test2; void test2(int a_var) { a_diff_var = "arbitrary"; }
job test3; void test3(int a_var) { var_30 = "Yup, still executing the same code around a different operation. Would be nice to refactor..."; }
job * tests[] = { test1, test2, test3, testn };
void Tests()
{
int i;
for (i=0; i < sizeof tests/sizeof tests[0]; i++) {
printf("This is the beginning, always constant.");
tests[i](a_var);
printf("End code, never changes");
a_var++;
}
}

Is this a good way for unconditional jump?

I have a function f( ) in a file func.c and functions f1( ), f2( ), f3() , f4( ) in another file funcs.h. (Assume that all the functions receive/return values without any loss of generality).
Function f( ) calls f4( )
f4( ) calls f1( ), f2( ), f3( ) in some arbitrary order, among themselves
At some point of time during the execution, f3() detects the completion of the algorithm and it has to "terminate" the execution of the algorithm. In a standalone case, it should exit out of the program after printing the solutions.But here, I need f3( ) to return to f( ).
This is my solution:
In this scenario, I cannot simply return to f4() (the original function called by f(), since there is already a function call stack of f1(), f2(), f3(),f4(), waiting to be "popped"). So, what I did is:
I did a setjmp( ) in f() before calling f4( )
And then, I did a longjmp( ) in f3( ) when I detected the completion of the algorithm
My question is: Is this the correct way to achieve this in this scenario?
TBH I personally find its better to return a bool from the function and if the return is true then return true from the function below and so on until it gets back to the original function. This unwinds the stack correctly, which im not sure setjmp/longjmp does.
In general though if you aren't going to go on and do stuff after the f() function returns it should work anyway. I'd just argue its not a very good way to do things as someone reading the code will not find it as obvious as the functions returning bool back up the stack.
You can use getcontext/setcontext. They may be viewed as an advanced version of setjmp/longjmp; whereas the latter allows only a single non-local jump up the stack, setcontext allows the creation of multiple cooperative threads of control, each with its own stack.
Also refer to other related calls such as makecontext(), swapcontext().
Here is one sample code to show how to use these functions (Sorry for bad coding). Hope this helps you.
#include <stdio.h>
#include <ucontext.h>
void func(void);
int x = 0;
ucontext_t context, *cp = &context;
int main(void) {
getcontext(cp);
if (!x) {
printf("getcontext has been called\n");
func();
}
else {
printf("setcontext has been called\n");
}
}
void func(void) {
x++;
setcontext(cp);
}
Output:
getcontext has been called
setcontext has been called
f4( ) calls f1( ), f2( ), f3( ) in some arbitrary order, among themselves
What do you mean by "arbitrary order"? Unless you're writing a multi-threaded program, the order in which 1,2, and 3 are called should be deterministic; functions are executed synchronously in C.
You didn't mention what you are doing or what algorithm are you implementing but...
You could use a global structure with function pointers which f1,f2,f3,f4 knows it existence and from f4() you call f1() doing something like:
global.functionPointers[0]("parameters.for.f1");
Don't you still need a flag to know that you shouldn't call f4 again the second time?
int solution_found=0;
f(){
setjmp();
if (!solution_found)
f4();
/* continue here... */
}
Apart from that, setjmp/longjmp may be expensive calls. They also have a price in terms of readability of your program. I would certainly consider having f1,... pop themselves out of the stack the normal way instead, if I was you.
I would do it something like this:
struct solution { ... }
solution *f() {
solution *result;
if (something) {
result = f3();
if (result != NULL)
return result;
}
else {
result = f3();
if (result != NULL)
return result;
}
return f();
}
Or whatever your algorithm might be.

How to call a function just before returning in C?

I'm trying to execute something at the end of a function just before it returns to the caller.
To Do so, I would like to override return in a certain context. The behavior should be the same as __cyg_profile_func_exit, but I would like to activate it only for some functions.
I don't know if it's possible using gcc builtins or this kind of thing.
Thanks.
GCC has an attribute for this, which calls a function when an automatic variable goes out of scope, passing it the address of that variable
void cleanup_fn(int *p) {
puts("cleanup called...");
}
void f(void) {
int p __attribute__((cleanup(cleanup_fn)));
puts("in f...");
}
int main(void) {
puts("calling f...");
f();
puts("out of it...");
return 0;
}
Output:
calling f...
in f...
cleanup called...
out of it...
Nope, not in C per se.
What you could do is write a #define macro RETURN:
#define RETURN(func) if(_DEBUG_) func; return ;
#define RETURNV(func, val) if(_DEBUG_) func; return val ;
(Warning, you probably want to think a little more about guarding special cases than I have.)
Otherwise, you would need to write something that mangled the code behind the scenes, which is what profilers do.

Resources