Home > Back-end >  the address of 'x' will always evaluate al 'true'
the address of 'x' will always evaluate al 'true'

Time:12-07

I have to define a function which checks, if a division is safe to operate or not. This is what I have wrote:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stddef.h>

bool safe_division(const int *x, const int *y, int *result){
    if(!(((&x || &y || &result) != NULL) || (*y == 0))){
        return false;
    } else{
        *result = *x / *y;
        return true;
    }
}

int main(void){
    int x = 2;
    int y = 1;
    int result = 2;

    int *px = &x;
    int *py = &y;
    int *presult = &result;

    if(safe_division(px, py, presult)){
        printf("why hello there\n");
    }

    return EXIT_SUCCESS;
}

The problem is the error I get from the compiler. I know that the problem lies in the if statement in the safe_division function. How do I solve this?

CodePudding user response:

The address of a variable is always non-null, so it doesn't make sense to check if it is null. What you actually want is to check if the value of a pointer variable is NULL.

Also, even fixing that, this doesn't do what you think it will:

(&x || &y || &result) != NULL

This first performs a logical OR of the pointer values, generating either the value 0 or the value 1, then checks to see if that value is NULL. What you want here is to compare each pointer value to NULL individually, then use a logical OR.

if ((x == NULL) || (y == NULL) || (result == NULL) || (*y == 0)) {

CodePudding user response:

logical or (||) between pointers does not do what you think, it actually performs OR betwen values and then single value is compared with NULL

you need to write like this:

if ((x == NULL) || (y == NULL) || (result == NULL) || (*y == 0)) {

shorter way is:

if (!x || !y || !result || !*y) {

  • Related