Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the address of 'x' will always evaluate al 'true'

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading