What is the meaning of NULL != value in C++? [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
I was going through a piece of C++ code and came across a code like
if (NULL != threadInfo)
{
...
...
}
I was just wondering is there any difference between using the expression
if (threadInfo != NULL)
{
...
...
}
what is said above.
While reading the first one reads " If NULL not equals to ThreadInfo" and the second one reads "If threadInfo not equals to NULL". To me the second one makes more sense.

No, there is no difference. In case of == there might be some difference. The thing is that if you accidentally write = instead of == the compiler will give an error in the first case.
if (threadInfo = NULL) //always false. The compiler will give you a warning at best
if (NULL = threadInfo) //Compiler error
I personally hate that practice and think it's better to write code that can be read in a normal human language, not Yoda language.

It's for safety, so you don't accidentally write
threadInfo = NULL
instead of
threadInfo == NULL
For the != there's no need to do this, but it's consistent.

If threadInfo is of a type that overrides operator !=, and the owner of that class has not provided a symmetric free function that handles the case where the two arguments are swapped, there might be a difference (there might also be a need to fire that programmer).
Otherwise, it's a matter of taste. Probably it will be preferred by people who write if(42 == answer) instead of if(answer == 42) -- this protects you from mistyping an assignment operator instead of an equals check. But since modern compilers warn you when you do that, it's debatable whether this approach offers anything.

There is no difference. The point of writing NULL != ... is that if you instead make a typo and write NULL = ... the code won't compile. If you had ... = NULL it could be a valid assignment and the error could go unnoticed (but most compilers detect this and warn you). Somebody once tried to insert a backdoor into the Linux kernel using this technique.
Also note that most persons don't code like that.

There is no difference, EXCEPT that the first option cannot be mistyped as:
if (threadInfo = NULL)
{
...
...
}
And some people don't know how to use compiler switches to check this (and some compilers don't have them).

No difference, this is so called Yoda coding convention.
if (NULL != threadInfo)
is equivalent to
if (threadInfo != NULL)
and to
if (threadInfo)

This is usually used as a convention, and has no distinct meaning by itself.
Because assignment occurs to lvals, and NULL is unassignable, this protects against the dreaded threadInfo = NULL when you meant threadInfo == NULL or threadInfo != NULL bug.
For more detail, see this wikipedia article section on left-hand comparisons

Both do the same thing. It is a style convention that was used to avoid typing mistakes as:
if (value=NULL) // assignment instead of == operator
{
}

These are exact equivalents in terms of logic.
The second is more intutive, when one may see the first is seen as more safe as it doesn't allows writing (threadInfo = NULL) erroneously, leading to a bug.

Null is a reference in the memory contains nothing but that nothing have an address to access it.
By that you can make a comparisons behind null to check if a certain object have a value or nothing.

I don't see any difference. However, the practice of writing NULL == someVar would save you from writing NULL = someVar if you forget typing the second =.

Related

What are the advantages or implications of using assert vs exit or vice versa?

As far as I understand, a call to assert(e), where e is a boolean expression, executes something roughly like if (!e) { printf("%s:%d: failed assertion `%s'\n", __FILE__, __LINE__, e); abort(); } which terminates the program abruptly if the given expression is not true.
On the other hand, instead of using assert, I could probably write something like if (!e) { fprintf(stderr, "custom error message.\n"); exit(1); } which naively feels like a more cleaner, nicer thing to do.
Ignoring that assert can be turned off globally using the NDEBUG flag, what other advantage do you think one has over the other? Have I got the distinction right, or are there conceptual differences between the two which I am unaware of that let the two ways of conditional program termination have their own niche use cases? If the latter, please explain. Thank you.
The biggest advantage of assert is that it makes one's intentions clear. If you see assert(some_condition) then you know what the author's intent was (i.e., some_condition is always true). With your inlined version, I can't assume intention until I actually read your if block, and realize you're going to display an error message and terminate the program.
Less important reasons include that assert reduces copy/paste errors, some_condition is turned into a string automatically (including preservation of variable names), and that tooling can understand it.
what other advantage do you think one has over the other?
A macro is used because you want to be able to remove it via conditional compilation. In other words, you don't want the code to even appear in the binary.
Have I got the distinction right, or are there conceptual differences between the two which I am unaware of that let the two ways of conditional program termination have their own niche use cases?
Well, exit() and abort() don't behave the same way even if you use 1 as a "unsuccessful" exit code. The latter is intended to kill the program right away without further work and possibly trigger a debugging prompt or save an image of the process space (although exactly what it does depends on the vendor providing it). The former calls the registered functions by atexit(). There are other ways of stopping, too, see quick_exit() and _Exit().
For C++, there are way more considerations on the behavioral difference, e.g. whether destructors for variables in the stack frame(s) are run, whether global destructors are run, what happens if an exception is thrown while doing that, etc.
'assert' is a code autotesting tool. Sometimes the program should not stop its work with on client side (release version) even if the condition leading to the execution of the assert was met.
For example:
switch(color)
{
case red:
//...
break;
case green:
//...
break;
default:
assert(false && "unexpected color value. 'enum color' was modified?");
}
another example:
if ( OkOrFailEnum::OK != result )
{
assert(false && "data access fail");
throw std::runtime_error("Can not get index " + std::to_string(index));
}
At the same time, 'assert' is a code commenting tool.
inline unsigned Sum(unsigned* pPos, unsigned* pOffset)
{
assert(nullptr != pPos); // \
assert(nullptr != pOffset); // | preconditions
assert(*pPos + *pOffset < *pOffset && "Overflow?"); // /
return *pPos + *pOffset;
}
The assert:
assert(*pPos + *pOffset < *pOffset && "Overflow?");
means, that the Sum(..) function does not works correctly with big sums and it have to do some check before call the function.

C++ creating object based on condition

I create an object based on a command line option.
In C++
Capture *cc = NULL;
if ( argv[2] == "capture" )
cc = new Capture(<some args>);
Now to use this at different parts of the code, should i create a CaptureStub that contains dummy functions so that null pointer is never accessed. Or is there an easier way?
Thanks
should i create a CaptureStub that contains dummy functions
You mean the Null Object Pattern? Yes that would be fine.
Or is there an easier way?
I'm not sure there's an easier way (Null object patterns is a pretty good way) but a very idiomatic way is to check for NULL
if (cc != NULL)
{
// do something with cc
}
First, your if condition will never be true, since the == compares the address of the string literal capture to the second command line argument. You'll want to change it to something like strcmp("capture", argv[2] == 0) or (string("capture") == string(argv[2])).
Second, I think we need to think through the semantics of what you want. What is the desired behavior if the 'capture' option is not specified? Do noithing? If not, then, as #Doug T. mentions, the Null Object pattern is a good choice, rather than sprinkling your code with comparisons to null.
Capture cc = NULL;
Ugh, that's not a pointer right there. If it compiles it's because the Capture class has an implicit constructor that accepts an int or pointer, or has an operator=.
To correct this use
Capture* cc = NULL;
After that, you should structure your code in a way that you only use the object if it is initialized. If it's not possible, then check every time before you do so.

Is it good practice to check for null and check object properties in the same if statement

Is it good practice to check for null and check object properties in the same if statement?
Consider the following code:
if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
// Don't buy his records
}
This particular code is in java and I know the expression is evaluated from left to right so technically it won't throw a NullPointerException but in general is this good practice in any language?
As you are using an OR statement there will be a NullPointerException if jamesBlunt is null. You should use and, because if the left statement is false, the whole expression will be false.
Use:
if (jamesBlunt != null && jamesBlunt.isReallyBad()) {
// Don't buy his records
}
When Java 7 is out, you could use the shortcut
if(jamesBlunt?.isReallyBad() {
// Don't buy his records
}
But until then the explicit check for null would be best practice. (In fact it would be best practice to not use jamesBlunt objects...)
I'll assume the || is a typo and you meant && :)
To answer your question: it depends.
Does it make sense for jamesBlunt to ever be null? If not, then it would be better practice to have something like this:
void buyARecord(Artist jamesBlunt) {
if (jamesBlunt == null) {
throw new IllegalArgumentException("James should never be null!");
}
}
If it does make sense for jamesBlunt to be null then your approach is fine, assuming null and isReallyBad mean the same thing semantically. If they mean different things semantically then you should probably not be combining them on one line.
You do need to be careful in other languages. Many (Java, C++, C# etc) will behave the same way, but some may evaluate from right-to-left or evaluate lazily. Take particular care with functional languages like Lisp and Scheme as they tend to behave differently to object oriented languages like Java and C#.
You want to use && instead of OR.
Yes, it is good practice to check for null in the same if statement, the alternative (nesting two ifs) is ugly because adds more indentation.
But checking before is also OK: specially if you want to do some error checking.
Personally, I would separate these. Null checking is the kind of thing one would do at the beginning of a function and is usually done to verify function parameters and are generally called "guard clauses". These checks will often raise an exception or return an error code as defined by the function.
These can lead to cleaner code below, avoiding multiple levels of nesting. It also prevents the need to repeat the null checks if there are other things you wish to test for on the object in question.

Is `std::string(strerror(errno))` dangerous?

At some places in my code, I print debug messages like this:
int ret = getLinkSpeed(device.getSysName(), linkSpeed);
if (ret < 0)
{
logDebug("Failed to obtain port speed for this device. Error: " + std::string(strerror(errno)));
}
From the documentation it is not entirely clear if strerror will return 0 under certain conditions (which would cause my code to crash). Does anyone know if it's safe?
Why not write a function to do this:
string ErrStr() {
char * e = strerror(errno);
return e ? e : "";
}
This is easy to use, self-documenting, can be adapted to reformat the output and covers the possibility that strerror() might return NULL (I don't know if it can).
Where you might get problems, is if you use a multi-threaded application. In this case, you need to use strerror_r
Good question (+1), the documentation seems quite vague. I'm not sure if there is a "harder" source, such as the POSIX specification for instance.
Thinking a bit pragmatically, here is GNU libc's implementation. It returns a pointer to a static string buffer, so it cannot return 0.
In response to p00ya's comment, the safe (and also very pragmatical, heh) thing to do in the face of conflicting, vague or incomplete specifications is of course to assume the worst, and
not assume that the return value will always be a valid string.

Nested If (x) checks - Better way to write this?

There are places where I check for valid pointers before I perform an operation with them; these checks can be nested pretty deeply sometimes.
For example, I have
if (a)
{
if (a->b())
{
if (a->b()->c())
{
a->b()->c()->DoSomething();
}
}
}
I really don't like the look of this. Is there a way to turn this into something more readable? Ideally,
if (a && a->b() && a->b()->c() )
{
...
}
would be great, but obviously would not work.
EDIT - nvm the example that I put up DOES work as everybody has pointed out. I did test it out to see if this works, but there was a bug in my code in my test. duh!
Why would the latter not work?
In C, && is a short-circuit operator, so it is evaluated from left to right, and if any evaluation is false, evaluation stops.
In fact, you could write:
a && a->b() && a->b()->c() && a->b()->c()->DoSomething();
Quoting from K&R1:
Expressions connected by && or || are evaluated from left to right, and it is guaranteed that evaluation will stop as soon as the truth or falsehood is known.
Therefore the latter example will work perfectly, as WhirlWind has noted.
1 The C Programming Language, Second Edition, Page 21.
Your second example does work in C/C++. It short circuits when the first FALSE value is hit.
You've seen from the other answers that using && will work, and will short-circuit the evaluation when a null pointer is encountered.
The uneasy programmer in me likes to avoid repeating method calls for tests like this since it avoids worrying if they are idempotent or not. One option is to rewrite like this
A* a;
B* b;
C* c;
if ((a=a()) && (b=a->b()) && (c=b->c())) {
c->doSomething();
}
Admittedly verbose and a bit clunky, but at least you know each method is called just once.
Why 'obviously would not work'? Since the && operator only evaluates the right term if the left is valid, the rewrite is perfectly safe.
Since you've already received the direct answer to your question I'll just mention that long chains of calls like you've got there are a code smell and you might consider a better design. Such a design might, in this case, include use of the null object pattern so that your call might just boil down to:
a->CDoSomething();
Chaining works, but it's not necessarily the best general-case answer, particularly because it obscures the failure point. I would instead suggest flattening the tests by inverting the logic so that it exits on failure.
if (!pa)
return Fail("No pa");
B* pb = pa->b();
if (!pb)
return Fail("No pb");
C* pc = b->c();
if (!pc)
return Fail("No pc");
pc->DoSomething();
Same thing, but flat and easy to read. Also, because it immediately handles the failure case, that doesn't get relegated to an else that you might never get around to writing.
In this example, I assumed you didn't want to just silently fail, so I added Fail as a helper that logs the text and returns false. You could also just throw an exception. In fact, if the various methods signaled their failure by throwing an appropriate exception instead of returning null, then all this would be unnecessary. If silent failure was desirable, then a null object pattern would be appropriate.
if (a && a->b() && a->b()->c()) { a->b()->c()->DoSomething(); }
C++ performs lazy evaluation so this will work. First, a would be evaluated and if it's 0 the whole condition is false so there will be no evaluation of the other parts.
This works for the || operator as well. If you write if (a || b), b won't be evaluated if a is true.
Second one will work provided you want to call only DoSomething().