Why a condition that contains a pointer always returns true?

Rubel Hosen

For example consider the following code. The pointer p points to the variable a that contains a nonzero value. Meaning, the condition should be true. So, if the program returns 1, I have no problem with that.

#include <iostream>

int main()
{
    int *p, a = 1;

    p = &a;

    if(p)
    {
        return 1;
    }

    return 0;
}

But for the following program the result is same too. Though the pointer this time points to a variable that contains 0. So, the condition should be false, but it is not.

#include <iostream>

int main()
{
    int *p, a = 0;

    p = &a;

    if(p)
    {
        return 1;
    }

    return 0;
}

So, what I am missing? Why the condition is always returning true? I am assuming the pointer has nothing to do with the value that it points to. Rather it is evaluating the condition on the basis of something else and I want to know that particular reason.

Rubel Hosen

if (p) does return true because if (p) is shortcut to if (p != nullptr).

pcontains the memory address of the variable a. In my machine that is 0x29fef8. Since nullptr is equivalent to 0 and p is not 0 thus the condition if (p != nullptr) evaluates to true. Thus the condition always returns true.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why clap contains_id() always returns TRUE?

Why this condition is always true?

Item::contains always returns true

why condition is always true in javascript?

Why my condition is always true

Why is this PHP if condition always true?

Why contains() method on ArrayList always returns false?

Why is my "if" condition (string comparison) always true?

Why does this IF FOUND have a condition that is always true?

Why is this Kotlin condition marked as always 'true'?

Why is the condition in this callback always returns false?

Mongo aggregate query Boolean condition always returns true

Contains always returns false

if condition always evaluating true

Term for an if condition that is always true

I can't understand why the condition is always true

If returns always true

HasFlag always returns True

If always returns true

isAuthenticated() always returns true

Why does Contains() return false but wrapping in a list and Intersect() returns true?

why does Powershell Test-Path -Isvalid always returns true

Why a function checking if a string is empty always returns true?

Using NPM `redis` package, .exists(...) always returns true. Why?

Why the hash command in bash always returns true for ./<something>

Why my C# Code Checker method always returns true?

javascript form validation always returns true even when condition matches and should returns false

VB.NET - List.Contains always returns false when it should be true

ifelse command always returns 0 if condition contains `years` function from package lubridate