0

I wrote the following code in order to understand setjmp and longjmp functions but I think the issue is unrelated to those functions. I am expecting the output to be:

function1
function2
function2

but I keep getting:

function1
function2
function1

as the out put. Code:

#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>

void f1(char * a);
void f2(char * a);

jmp_buf buf1;

int main(int argc, char *argv[])
{
   char * w;
   f1( w);
   return 0;
}

void f1(char * a)
{
   a = "funtion 1";
   printf("%s\n",a);

   int i = setjmp( buf1 );
   if( i == 0 )
      f2( a );

   printf("%s\n", a);

}

void f2(char * a)
{
   a = "function 2";
   printf("%s\n",a);
   longjmp( buf1 , 2 );
}

What am I doing wrong here ? Thanks for any help.

Jenna Maiz
  • 792
  • 4
  • 17
  • 38
  • What you did wrong was to overwrite `char *a`. – Paul Ogilvie Mar 18 '16 at 16:36
  • 1
    `int i = setjmp( buf1 );` you cannot use the "return value" from setjmp() in an assignment (in this case the initialiser is an assignment), only to test it in a if or switch condition (maybe even while/do/for) – joop Mar 18 '16 at 17:53
  • See for instance http://stackoverflow.com/q/12204143/2235885 – joop Mar 18 '16 at 18:08

1 Answers1

3

There is no pass by reference in it's only pass by value. However, you can pass a pointer to the pointer in main(), like this

int main(int argc, char *argv[])
{
   char *w;
   f1(&w);
   return 0;
}

void f1(char **a)
{
   *a = "funtion 1";
   printf("%s\n", *a);

   int i = setjmp( buf1 );
   if (i == 0)
      f2(a);
   printf("%s\n", *a);

}

void f2(char **a)
{
   *a = "function 2";
   printf("%s\n", *a);
   longjmp(buf1 , 2);
}

NOTE: Be very careful with this, you are assigning a string literal and you shall not attempt to modify it.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97