Troubles with dereferencing a null


#1

I am having a little trouble with this section…
i thought the if statement needs an expression like <,>,= etc. to make a true/false decision.

if (ftPtr) { printf("Storing %.0f to the address %p\n", feet, ftPtr); *ftPtr = feet; }

what is the if statement evaluating?
thanks.


#2

An if statement needs an expression to test the value of in order to decide what to do next.

In your example, the expression is ftPtr, a simple expression.

if (Expression) Statement
if (Expression) Statement else AlternativeStatement

If the value of the Expression is not zero, then the if statement executes the Statement.

For example:

Print 1:

...
int bit = 1;

if (bit) {
    printf ("1");     // this statement gets executed because bit is not zero
}

Print either 0 or 1:

int bit = arc4random_uniform (2);

if (bit) {
    printf ("1");
}
else {
    printf ("0");
}

The important thing to know is what constitutes an Expression. Simple expressions can be combined with operators to form a compound expression.

if (bit > 0) {
    printf ("1");
}
else {
    printf ("0");
}

#3

[quote=“howdydoody2”]I am having a little trouble with this section…
i thought the if statement needs an expression like <,>,= etc. to make a true/false decision.

if (ftPtr) { printf("Storing %.0f to the address %p\n", feet, ftPtr); *ftPtr = feet; }

what is the if statement evaluating?
thanks.[/quote]

If I understand it correctly, a good way to think about it is

if (this is a thing / exists) {(/*then do this*/); *the thing* }

So if the thing in parenthesis is an actual thing, then it will execute what’s next. So it checks to see if *ftPtr is an actual thing, that it exists, and as long as it does, it will print the string that was written out.


#4

I was confused too at first. Tested this code out myself and its a lot clearer to me now. Hope this helps.

int g;
if(g){
printf (“g exist \n”);}

Does not print

int g = 1;
if(g){
printf (“g exist \n”);}

Print - g exist