Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable showing abrupt behavior

here is my code.

#include <stdio.h>
#define MAX(a,b) ((a)>(b)?(a):(b))
#define SZA(a) (sizeof(a)/sizeof(a[0]))

int anish=0; // global variable showing abrupt behaviour
int a[]={0,1,5,8,9,10,17,17,20,24,30};
int n= SZA(a);

int cache[100];
int road(int len)
{
    anish++;

    if(cache[len]!=-1)
        return cache[len];
    if(len<=0)
        return 0;
    int max=0;
    int i;
    for(i=1;(i<n && len>=i);i++)
    {
        max=MAX(max,a[i]+road(len-i));
    }
    return cache[len]=max;
}

void f()
{
    anish=13;
}

int main()
{
    int i;
    for(i=0;i<=13;i++)
        cache[i]=-1;
    int len=10;
    // f();

    printf("%d %d\n",road(len),anish);
    return 0;
}

In this, road() is a recursive function and I want to calculate the number of times this function is being executed. So, I am doing this via a global variable anish. But the value of anish is not changing in this road() function, while in function f() value of anish is being modified.

Any reason for this absurd behavior?


2 Answers

your c code shows an outdated anish variable succesive printf's shows different value

this has something to do with c's internals

it has something to do with this : Parameter evaluation order before a function calling in C

loki astari said:

The order that function parameters are evaluated is unspecified behavior. (This won't make your program crash, explode, or order pizza... unlike undefined behavior.)

The only requirement is that all parameters must be fully evaluated before the function is called.

like image 69
maazza Avatar answered Mar 09 '26 15:03

maazza


In

printf("%d %d\n",road(len),anish);

the order in which the arguments are evaluated is unspecified. In this case, it seems anish is evaluated before road(len), so the value passed to printf is the unmodified value.

Evaluate road(len) before calling printf and store the result in a temporary variable.

like image 37
Daniel Fischer Avatar answered Mar 09 '26 15:03

Daniel Fischer