Search code examples
c++booleanbitwise-ortypecasting-operator

integer is not getting typecasted to bool in c++


While coding, I encountered runtime error. This is my code:

int f(int a[],int n,int sum)
{
    int dp[sum+1][n+1];
    for(int i=0;i<=n;i++)
    dp[0][i]=1;

    for(int i=1;i<=sum;i++)
    dp[i][0]=0;

    for(int i=1;i<=sum;i++)
    {
        for(int j=1;j<=n;j++)
        {
            dp[i][j]=dp[i][j-1];
            if(i>=a[j-1])
            dp[i][j]=(dp[i][j])^(dp[i-a[j-1]][j-1]);
        }
    }

    return dp[sum][n];
}

Here sum is always positive. After a lot of debugging I could not get answer So after matching my answer from solution. This is the answer.

bool f(int a[],int n,int sum)
{
    bool dp[sum+1][n+1];
    for(int i=0;i<=n;i++)
    dp[0][i]=true;

    for(int i=1;i<=sum;i++)
    dp[i][0]=false;

    for(int i=1;i<=sum;i++)
    {
        for(int j=1;j<=n;j++)
        {
            dp[i][j]=dp[i][j-1];
            if(i>=a[j-1])
            dp[i][j]=(dp[i][j])||(dp[i-a[j-1]][j-1]);
        }
    }

    return dp[sum][n];
}

So my question is why int cannot be converted to bool. P.S. : Instead of || I also tried | as this is bitwise operator but still I get runtime error. Someone please help me get the answer.


Solution

  • The most likely cause of the runtime error seems to be the line

    dp[i][j]=(dp[i][j])^(dp[i-a[j-1]][j-1]);
    

    And most likely the dp[i-a[j-1]], which gets the index depending on the value in the a array. This can easily result in dp being indexed by a negative value.

    This suspicion is also backed by the fact that it "works" with || (logical or) but does not work with either ^ or | (binary operators). This is because the logical operators have short-circuit evaluation (if the dp[i][j] is true, the second operator does not need and is not evaluated at all), whereas the binary operators always evaluate both operands.

    So it seems that in the case of || the second operand is not evaluated thus it does not crash, whereas with the binary operators it is evaluated and the index goes out of bounds and crashes the app.