How should I test for a null pointer?

K

Keith Thompson

Anand Hariharan said:
How should I test for a null pointer within a C program?

Presumably the following will work:
[snip]

if ( !ptr ) { dosomething }

My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?

I find "if not non-null pointer" quite awkward.

I read it as "if not ptr" or "if not pointer". I have to mentally
redefine the usual meaning of "not" for this to make sense. It's not
a real problem, but personally I prefer "if (ptr == NULL)".
 
S

Seebs

I read it as "if not ptr" or "if not pointer". I have to mentally
redefine the usual meaning of "not" for this to make sense. It's not
a real problem, but personally I prefer "if (ptr == NULL)".

Oddly, that fits my sense of "not", so it doesn't require redefinition to
me. I don't see a cognitive difference between:
x = count(kitties);
if (x) {
}

and
x = ptr_to_kitties();
if (x) {
}

They're both doing something if there were kitties.

-s
 
J

Julienne Walker

Anand Hariharan said:
On Mar 21, 3:08 am, (e-mail address removed) (Mark
Hobley) wrote:
How should I test for a null pointer within a C program?
Presumably the following will work:
[snip]
if ( !ptr ) { dosomething }
My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?
I find "if not non-null pointer" quite awkward.
FWIW: "if not ptr" where I usually vocalise "ptr" as "pointer".

Why not spell it out as I do consistently in my "convoluted" code
after my pre-Szymonyi Hungarian?

Why spell it out when the abbreviation is commonly known? In the case
of a subjective and supremely trivial matter, it's best to simply let
people do what they want and focus on more important issues. Pick your
battles unless you have nothing better to do than fight for fun.

For questions like the OP's, the best you can do is collect a number
of personal opinions and reach no conclusion. As such, I'll add to the
noise with my preference of being explicit when the object isn't
strictly boolean:

if ( ptr == NULL ) { /* ... */ }

With "ptr" as a generic placeholder for a more informative name. For
boolean objects it's a different matter:

if ( !done && is_valid ) { /* ... */ }
 
A

Anand Hariharan

Anand Hariharan said:
How should I test for a null pointer within a C program?
Presumably the following will work:
if ( !ptr ) { dosomething }
My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?
I find "if not non-null pointer" quite awkward.

I read it as "if not ptr" or "if not pointer".  I have to mentally
redefine the usual meaning of "not" for this to make sense.  It's not
a real problem, but personally I prefer "if (ptr == NULL)".

I suppose that sounds very similar to "if naught pointer" or "if
nought pointer" which is close enough to the actual semantics?
 
D

Dr Malcolm McLean

Why spell it out when the abbreviation is commonly known?
Quite a few coding standrards say that "ptr" is an unacceptable name
for a pointer.

Now imagine you want to do, the following, write a qsort() replacement
that passes a pointer to the comparision function (as well as the two
data pointers), in order to allow for context-dependent comparisions
without using a global.
I'd write that as

void qsort2(void *data, int N, size_t s, int (*compfunc)(const void
*e1, const void *e2, void *ptr), void *ptr);

However "ptr" is banned. So "pointer" is an acceptable substitute.
 
B

Ben Pfaff

Dr Malcolm McLean said:
Quite a few coding standrards say that "ptr" is an unacceptable name
for a pointer. [...]
However "ptr" is banned. So "pointer" is an acceptable substitute.

It's hard for me to imagine why "ptr" would be banned and not
"pointer". It's quite clear that "ptr" stands for "pointer" and
it is a few characters shorter.
 
S

Stephen Sprunk

The "if (ptr == NULL)" construction looks excessively verbose to me,
though I wouldn't bother changing it if I ran across it--unless the
project style guide said it was wrong, of course. I always write "if
(!ptr)" myself, and I've never had anyone reject it in a code review;
even if one doesn't like that form, one has to admit it's idiomatic.

True, but IMHO the pointer-ness of the variable should be obvious from
either naming or context; if not, you need more than little tricks like
that to fix the code.
I'm fine with using booleans this way, just not pointers

if (!ptr), doesn't read as "if not pointer". I suppose I could read
it as "if null-pointer"

I actually do pronounce "if (!ptr)" as "if not pointer"; I've seen the
construction so many thousands of times it makes sense to me when said
that way. Such is the power of following common idioms.

One could also read it as "if not valid pointer", but that's not
technically correct since ptr could be indeterminate, i.e. neither valid
nor null. Boolean operators tend to generate such false dichotomies all
over the place.

S
 
S

Seebs

(I just had to quote that, because WTF. "Hungarian" is known as that
because it was named after Szymonyi.)
Why spell it out when the abbreviation is commonly known?

Significantly:

* Human readers make more mistakes on longer words.
* Abbreviations help people read quickly and accurately.

So there's a lot to be said for picking consistent abbreviations.
The loop index "i" is not just some kind of short-cut; it improves
reliability and legibility of code.
In the case
of a subjective and supremely trivial matter, it's best to simply let
people do what they want and focus on more important issues. Pick your
battles unless you have nothing better to do than fight for fun.

Consider to whom you were responding.

-s
 
S

Seebs

(Hungarian guy here.) That's actually "Simonyi". It's pronounced
"scimogni" if you read Italian, or "shimonyi" in English, the "ny" being
pronounced like in Banyan VINES.

Whoops! I'm very sorry. I even knew that looked funny, but in an
inexplicable moment of madness, I thought I'd just assume that Nilges
had gotten a fact right.

I have no idea why I thought that.

I should probably have just trusted my instinct to go look up the spelling,
especially in context.

-s
 
H

Hamiral

William said:
But as pointed out elsethread (ptr) is equivalent to (ptr != 0), which is a
boolean expression. An if statement condition is a boolean expression by
definition.

But ptr alone is not a boolean expression. It's a pointer, which should
be (to my mind) be tested against NULL. (ptr == NULL) is a boolean
expression. Using (ptr == NULL) clearly shows that you're dealing with a
pointer, whereas (!ptr) doesn't.
I meant that booleans variables (things like ok, done, etc) should not
be tested against TRUE or FALSE.

Ham
 
H

Hamiral

Anand said:
How should I test for a null pointer within a C program?

Presumably the following will work:
[snip]
if ( !ptr ) { dosomething }

My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?

I find "if not non-null pointer" quite awkward.

I read it "if not pointer", which doesn't make sense to me. I prefer
reading "if pointer is not assigned" for if(ptr == NULL)

Ham
 
P

Phil Carmody

Nope:
"""
6.8.4 Selection statements
....
if ( expression ) statement
....
the first substatement is executed if
the expression compares unequal to 0.
"""

The expression that lies within the brackets is compared to zero.

I.e. the thing you give it is not necessarily a boolean expression,
a boolean may be only arrived at by subsequent comparison of your
expression to 0.
But ptr alone is not a boolean expression. It's a pointer, which
should be (to my mind) be tested against NULL. (ptr == NULL) is a
boolean expression. Using (ptr == NULL) clearly shows that you're
dealing with a pointer, whereas (!ptr) doesn't.

Then name your variables sensibly enough that you know ptr is a
pointer without having to throw redundant operands into your
conditions.
I meant that booleans variables (things like ok, done, etc) should not
be tested against TRUE or FALSE.

That I agree with, but as the if() tests them against the only false
value, 0, anyway, there's no point in going out of your way to collapse
the expression onto a boolean one unnecessarily.

Phil
 
D

Dr Malcolm McLean

So there's a lot to be said for picking consistent abbreviations.
The loop index "i" is not just some kind of short-cut; it improves
reliability and legibility of code.
Exactly. The conventions are still developing (eg you can't easily use
i in Matlab because it thinks you mean root minus one), but it seems
obvious that short conventional symbols (x, y, i, N, ptr, str, theta,
t, temp) are better than long names that form English words. The
reason is that expressions can get fairly complex.

I use ii, iii, iv, v for inner loops. However j, k, l is more normal.
I use j when I need a second counter for the same level of loop, eg if
we need to count backwards as well as forwards over an array.
 
K

Keith Thompson

William Ahern said:
In `if (ptr) { ... }' ptr is a boolean expression because an if statement
conditional must be boolean.

No, the expression in an if statement merely needs to be a scalar.

C99 6.8.4.1 The if statement:

Constraints

The controlling expression of an if statement shall have
scalar type.

Semantics

In both forms, the first substatement is executed if the
expression compares unequal to 0.

where "both forms" refers to if vs. if-else.

Prior to C99, C didn't even have boolean expressions.

My own personal preference is that the expression in an if statement
should be, in some sense, *logically* boolean. That is, the
expression should represent a false/true condition; if it evaluates to
zero, the condition is false, and if it evaluates to any non-zero
value, the condition is true, with no meaningful distinction among
different non-zero values.

If there is such a distinction, I prefer to explicitly compare the
result to zero, so that the result of that comparison is "logically
boolean". Thus:

if (ptr !== NULL) /* different non-null pointers are distinct */
if (x != 0.0)
if (c != '\0')
if (count != 0)
if (strcmp(s1, s2) != 0) /* distinct non-0 values mean different things */
if (done)
if (isdigit(c)) /* logically boolean, even if it's neither 0 nor 1 */

Again, this is nothing more than my own personal preference.
I understand and accept that it's not supported by the langauge
standard, and that that not everyone shares it.
 
K

Keith Thompson

Phil Carmody said:
Nope:
"""
6.8.4 Selection statements
...
if ( expression ) statement
...
the first substatement is executed if
the expression compares unequal to 0.
"""

The expression that lies within the brackets is compared to zero.

I.e. the thing you give it is not necessarily a boolean expression,
a boolean may be only arrived at by subsequent comparison of your
expression to 0.

And even then, the comparison (assuming it's done via the "!="
operator) yields a result of type int. (An admittedly minor point.)

[...]
 
K

Keith Thompson

Hamiral said:
Anand said:
How should I test for a null pointer within a C program?

Presumably the following will work:
[snip]
if ( !ptr ) { dosomething }

My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?

I find "if not non-null pointer" quite awkward.

I read it "if not pointer", which doesn't make sense to me. I prefer
reading "if pointer is not assigned" for if(ptr == NULL)

ptr = NULL; /* ptr has now been assigned */
if (ptr == NULL) ... /* ? */
 
S

spinoza1111

(I just had to quote that, because WTF.  "Hungarian" is known as that
because it was named after Szymonyi.)

As I have said, Charles Szymonyi stole this idea from his tenure at
IBM. "Hungarian" notation in the sense of a systematic prefix was in
use as early as 1962, for it appears in a book on coding standards
that was published in 1963 by Dick Brandon ("Management Standards for
Data Processing"), a book I used to own.

[I got the original reference wrong: the book was published in 1963,
not 1962 and although Dick Brandon was part of the Diebold group, he
and not Diebold was the author.]

That book showed a method for indicating the type and usage of
assembler language symbols in IBM 1401 that was later used in IBM 360
series Basic Assembler Language as a standard, and Szymonyi apparently
stole this idea and used it unethically as the basis of a PhD thesis
where a PhD thesis must be original work. Szymonyi worked for a while
at IBM after escaping Hungary, but was as maladjusted there as he was
under Goulash Communism.

I was already using it as a programmer and manager at Roosevelt
University in 1973.

However, one reason why I am happy, today, to be out of the field is
the lack of simple ethics of people like you and Szymonyi. I believe
you, Dweebach, submitted pseudo.c here to get your poorly written
(fallthrough case) C code fixed on behalf of Wind River Systems by
slaves.

This starts in the lead comment, where you at one and the same time
copyright the code on behalf of Wind River and then say it's a GNU
public license. If you knew your job, you'd know that copyright and
copyleft are incompatible, as incompatible as "clear" and "wrong".
Significantly:

* Human readers make more mistakes on longer words.

No, just ADHD dweebs.
* Abbreviations help people read quickly and accurately.

Abbreviations are too local to languages and cultures. We can in a
globalized world expect programmers world wide to have command of the
English I teach today, which is world received English and rather
different from American English: for example, you don't say
"Manchester United wins", you say "Manchester United win", since a
football team is eleven lads. Therefore it is culturally insensitive
and productive of incomprehensible code to use abbreviations based on
American English.
 
S

spinoza1111

Anand Hariharan said:
On Mar 21, 3:08 am, (e-mail address removed) (Mark
Hobley) wrote:
How should I test for a null pointer within a C program?
Presumably the following will work:
[snip]
if ( !ptr ) { dosomething }
My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?
I find "if not non-null pointer" quite awkward.
I read it as "if not ptr" or "if not pointer".  I have to mentally
redefine the usual meaning of "not" for this to make sense.  It's not
a real problem, but personally I prefer "if (ptr == NULL)".

I suppose that sounds very similar to "if naught pointer" or "if
nought pointer" which is close enough to the actual semantics?

Sounds like a Yorkshire joke: salesman pokes his head into an office
in Manchester: "aught?" Manager replies "nought!"

If you use naught, American programmers won't understand you, if that
bothers you.
 
S

spinoza1111

On Mar 21, 3:08 am, (e-mail address removed) (Mark
Hobley) wrote:
How should I test for a null pointer within a C program?
Presumably the following will work:
[snip]
if ( !ptr ) { dosomething }
My follow-up question to the group is, how do you read the above line
of code in your head (or out loud)?
I find "if not non-null pointer" quite awkward.
FWIW: "if not ptr" where I usually vocalise "ptr" as "pointer".
Why not spell it out as I do consistently in my "convoluted" code
after my pre-Szymonyi Hungarian?

Why spell it out when the abbreviation is commonly known? In the case

See the discussion below. My international software and English
teaching experience has taught me not nought but aught, to be very
dubious about propositions to the effect that "everybody", even by gum
people in the next county, understands some abbreviation.
of a subjective and supremely trivial matter, it's best to simply let
people do what they want and focus on more important issues. Pick your
battles unless you have nothing better to do than fight for fun.

Julienne, I am not "fighting for fun". There are some very evil things
going on in this newsgroup. Real thugs and head cases (Colonel Harlan
Sanders and Reid) are coming in here ONLY to savage people because
they are twisted head cases and closet queers. Seebach and Wind River
seem to be here to steal intellectual production from (unwitting)
slaves in order to fix, without credit or financial compensation,
amateurish errors in Seebach's code. Seebach is calling me "insane"
and a "moron" for making errors while consistently posting code
snippets and code ridden with errors he cannot fix. Heathfield is
still disrupting conversations possibly in the employ of a publisher
who jailed a friend of mine in Chicago several years ago when she
tried to get money owed her.

One reason I left the field was that in 1980 I joined a company in
which the evil was plain, but everybody, especially female employees,
spoke in dulcet tones and looked the other way when whistle blowers
were escorted from the building. I am too old and yet too employable
in other fields than programming to not speak out here.
For questions like the OP's, the best you can do is collect a number
of personal opinions and reach no conclusion. As such, I'll add to the
noise with my preference of being explicit when the object isn't
strictly boolean:

if ( ptr == NULL ) { /* ... */ }

With "ptr" as a generic placeholder for a more informative name. For
boolean objects it's a different matter:

if ( !done && is_valid ) { /* ... */ }

Basically, I prefer my pre-Szymonyi Hungarian standard (ptrIndex1...).

This is because it reconciles left-brain thinking (in the prefix) with
right brain thinking in the more evocative suffix that can be
pronounced.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,252
Latest member
MeredithPl

Latest Threads

Top