Understanding some code

Started by
13 comments, last by rip-off 15 years, 4 months ago
Quote:Original post by Eeyore
Hey all, I just wanted some help understanding some code.

const char *cmd = argv[0] && *argv[0] ? argv[0] : "git-help";

This is logically equivalent to:

const char *cmd;if (argv[0] != NULL){	if (*argv[0] != NULL)	{		cmd = argv[0];	}	else	{		cmd = "git-help";	}}else{	cmd = "git-help";}


That is because of the early-out of the && operator. If the left condition fails, it will never check/execute what's on the right side.
Advertisement
NULL is typically used with pointer values. As such, I would use the NUL character for the second condition:
const char *cmd = "git-help";if (argv[0] != NULL){	if (*argv[0] != '\0')	{		cmd = argv[0];	}}
Quote:Original post by rip-off
NULL is typically used with pointer values. As such, I would use the NUL character for the second condition:


Just an addendum: "Should I use NULL or 0?"

Quote:Original post by rip-off
NULL is typically used with pointer values. As such, I would use the NUL character for the second condition.

You're absolutely right. However, I was just demonstrating what the logic behind the original and somewhat hard-to-understand statement was, by translating it to an equivalent if/else block. And the original code does in fact check that both argv[0] && *argv[0] have non-0 values, which is equivalent to != NULL if NULL is defined as 0. :)
NULL may be 0, but my point is about intent. When I see something compared with NULL, I'm going to assume that the other thing is a pointer. If I see it compared with '\0' then my assumption is that the other thing is a character. That is all [smile]

This topic is closed to new replies.

Advertisement