Are there technical differences between "cond && {...}" and "if (cond) { ...}"? - if-statement

Sometimes when I'm reading through other people's code (specifically PHP, but this question refers to all programming languages), I see something like the following:
some_bool_value && return = some_function()
After some thought, I realized that they were using this in place of:
if(some_bool_value){ return = some_function() }
Is there any programmatic benefit to this alternative method, or is it just a shorthand/preference?

It is programmers shorthand. In this case, it is known as short-circuit evaluation (If the left side of the && evaluates to true/non-zero, the right side is evaluated. Otherwise, the right side is not evaluated).
This type of thing falls under personal preference and style of the programmer or team and is not related to efficiency in any practical sense.

Related

difference between if(pointer) vs if(pointer != NULL) in c++, cpplint issue

I already checked this post Can I use if (pointer) instead of if (pointer != NULL)? and some other posts on net.
But it is not stating any difference between two statements.
Problem: As I run cpplint.py on my cpp code, I found issues where I check pointers for NULL.
I preferred to check using simple
if(pointer) //statement1
but cpplint says you should check like
if(pointer != NULL) //statement2
So I just want to know , Are there any benefits of statement2 over statement1 ? Are there some scenarios in which statement1 may create problem ?
Working: As per my knowledge there is no difference in working of both statements. Its just a change of coding style.
I prefer to use like statement1, because
Its Simple, Readable
No Tension of missing (=) by mistake over equality(==) in a comparison
But cpplint is raising this as issue, then there might be some benefit that I missed.
Note: Java also doesn't support statement1.
No, if pointer is really a pointer type there is no difference, so everything here is a question of coding style. Coding style in turn depends on habits in different communities so there can't be a general recommendation.
I personally prefer the first because it is shorter and more to the point and avoids the use of the bogus macro NULL.
In C NULL can be very different things (integer or pointer) and in C++ its use is even deprecated nowadays. You should at least use nullptr, there.
You are using Hungarian notation, where it's possible to tell if a variable is a pointer. As long as it is - either native or smart - there's no difference. However, when someone changes it to another indirect type (e.g., std::optional<>), then the second will fail. So my suggestion is to keep on using the first: it's not Java, it's C++.
In C++, assuming ptr is a pointer, the comparisons if (ptr) and if (ptr != NULL) are functionally equivalent.
In C++11 and later, it is often considered preferable to use the alternative if (ptr != nullptr).
For a simple check of a pointer, the differences in these options are really stylistic. The mechanisms might differ slightly, but the end result is the same.
cpplint, like most automated checkers, tends to - by default - complain more about breaches of some style guidelines more than others. Whether any particular set of guidelines is right or wrong depends on what is needed for your project.
For class types that can sensibly be compared with a pointer (e.g. smart pointer types) the preferred test depends on what set of operations (comparison operators, implicit conversions, etc) that type supports.
In C, onsider :
int *ptr=malloc(10*sizeof *ptr);
free(ptr); // though the memory is freed, the ptr is not auto-set to NULL
if (ptr)
{
printf ("ptr is not null\n");
}
So you are expected to put
ptr=NULL; // ptr is explicitly made to point at nothing
// The above step is mandatory.
after the free.
So as a response in the the if-statement, one might recommend to do
if ( ptr == NULL ) // This is mostly a coding style & improves readability?
or better
if ( NULL == ptr ) // less chances of error
Well, the [ site ] says about cpplintthat it is :
An automated checker to make sure a C++ file follows Google's C++ style guide
So again, it is somebody's style that matters. Say , if you contribute to somebody's code in google, they expect you to follow this style where it facilitates easy collaboration.
There is one scenario that may create a problem using statement1.
Consider the following code which could have two different meanings.
bool* is_done = ...;
// Is this checking if `is_done` is not null, or actually
// intended to check if `*is_done` is true?
if (is_done) {
...
}
If you intended to do a null check, you're fine. But if your original intent is to check if *is_done is true but missed an asterisk by accident, this code may result in a totally unwanted behavior and require you to spend X hours to figure out the culprit.
This could've avoided by explicitly checking the statement like
// Now this results in a compile error and forces you to write
// `*is_done` instead.
if (is_done == true) {
...
}
This is applicable to any types that could be implicitly converted to bool like std::unique_ptr.
Someone may argue that the above case is too rare and still prefer the statement1 in favor of simplicity. I think it is fair and both styles are acceptable. But some organizations, like Google, may encourage you to follow their coding style to keep the lesson they previously learned.
There is no difference between both if(pointer) and if(pointer != NULL). if(pointer) is used for the code optimization.

What is the difference between these (bCondition == NULL) and (NULL==bCondition)? [duplicate]

This question already has answers here:
What's the reasoning behind putting constants in 'if' statements first?
(8 answers)
Closed last month.
While exploring msdn sites ,most of the condition checking places they are using (NULL == bCondition).
what is the purpose of using these notations?
Provide some sample to explain these please.
Thanks.
The use of NULL == condition provides more useful behaviour in the case of a typo, when an assignment operator = is accidentally used rather then the comparison operator ==:
if (bCondition = NULL) // typo here
{
// code never executes
}
if (NULL = bCondition) // error -> compiler complains
{
// ...
}
C-compiler gives a warning in the former case, there are no such warnings in many languages.
It's called Yoda Conditions. (The original link, you need high rep to see it).
It's meant to guard against accidental assignment = in conditions where an equality comparison == was intended. If you stick to Yoda by habit and make a typo by writing = instead of ==, the code will fail to compile because you cannot assign to an rvalue.
Does it worth the awkwardness? Some disagree, saying that compilers do issue a warning when they see = in conditional expressions. I say that it simply happened just two or three times in my lifetime to do this mistake, which does not justify changing all the MLOCs I wrote in my life to this convention.
There is no difference. It is an ancient way of defensive programming that has been obsolete for over 20 years. The purpose was to protect from accidentally typing = instead of == when comparing two values. Pascal programmers migrating to C were especially prone to write this bug.
From Borland Turbo C released in 1990 and forward, every known compiler warns against "possibly incorrect assignment", when you manage to type out this bug.
So writing (NULL == bCondition) is not better or worse practice than the opposite, unless your compiler is extremely ancient. You don't need to bother about writing them in any particular order.
What you should bother with, is to adapt a coding style where you never write assignments inside if/loop conditions. There is never a reason to do so. It is a completely superfluous, risky and ugly feature of the C language. All industry de-facto coding standards ban assignment inside conditions.
References:
MISRA C:2004 13.1
CERT C EXP18-C
Many people prefer writing NULL == bCondition so that they accidently don't assign the NULL value to bCondition.
Because of typo it happens that instead of writing
bCondition == NULL
they end up writing
bCondition = NULL // the value will be assigned here.
In case of
NULL = bCondition // there will be an error
It's simply a good defensive measure. Some may also find it more convenient to read. In case of a mistyped assignment instead of the equality operator, the compiler will attempt to modify NULL, which is not an lvalue and will produce an error message. When using bCondition = NULL, the compiler might produce a warning about using an assignment as a truth value, a message which can get lost and go unnoticed.
While usually there is no difference between variable == value and value == variable, and in principle there shouldn't be, in C++ there sometimes can be a difference in the general case if operator overloading is involved. For example, although == is expected to be symmetric, someone could write a pathological implementation that isn't.
Microsoft's _bstr_t string class suffers from an asymmetry problem in its operator== implementation.

Checking for NULL pointer in C/C++ [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In a recent code review, a contributor is trying to enforce that all NULL checks on pointers be performed in the following manner:
int * some_ptr;
// ...
if (some_ptr == NULL)
{
// Handle null-pointer error
}
else
{
// Proceed
}
instead of
int * some_ptr;
// ...
if (some_ptr)
{
// Proceed
}
else
{
// Handle null-pointer error
}
I agree that his way is a little more clear in the sense that it's explicitly saying "Make sure this pointer is not NULL", but I would counter that by saying that anyone who's working on this code would understand that using a pointer variable in an if statement is implicitly checking for NULL. Also I feel the second method has a smaller chance of introducing a bug of the ilk:
if (some_ptr = NULL)
which is just an absolute pain to find and debug.
Which way do you prefer and why?
In my experience, tests of the form if (ptr) or if (!ptr) are preferred. They do not depend on the definition of the symbol NULL. They do not expose the opportunity for the accidental assignment. And they are clear and succinct.
Edit: As SoapBox points out in a comment, they are compatible with C++ classes such as unique_ptr, shared_ptr, auto_ptr that are objects that act as pointers and which provide a conversion to bool to enable exactly this idiom. For these objects, an explicit comparison to NULL would have to invoke a conversion to pointer which may have other semantic side effects or be more expensive than the simple existence check that the bool conversion implies.
I have a preference for code that says what it means without unneeded text. if (ptr != NULL) has the same meaning as if (ptr) but at the cost of redundant specificity. The next logical thing is to write if ((ptr != NULL) == TRUE) and that way lies madness. The C language is clear that a boolean tested by if, while or the like has a specific meaning of non-zero value is true and zero is false. Redundancy does not make it clearer.
if (foo) is clear enough. Use it.
I'll start off with this: consistency is king, the decision is less important than the consistency in your code base.
In C++
NULL is defined as 0 or 0L in C++.
If you've read The C++ Programming Language Bjarne Stroustrup suggests using 0 explicitly to avoid the NULL macro when doing assignment, I'm not sure if he did the same with comparisons, it's been a while since I read the book, I think he just did if(some_ptr) without an explicit comparison but I am fuzzy on that.
The reason for this is that the NULL macro is deceptive (as nearly all macros are) it is actually 0 literal, not a unique type as the name suggests it might be. Avoiding macros is one of the general guidelines in C++. On the other hand, 0 looks like an integer and it is not when compared to or assigned to pointers. Personally I could go either way, but typically I skip the explicit comparison (though some people dislike this which is probably why you have a contributor suggesting a change anyway).
Regardless of personal feelings this is largely a choice of least evil as there isn't one right method.
This is clear and a common idiom and I prefer it, there is no chance of accidentally assigning a value during the comparison and it reads clearly:
if (some_ptr) {}
This is clear if you know that some_ptr is a pointer type, but it may also look like an integer comparison:
if (some_ptr != 0) {}
This is clear-ish, in common cases it makes sense... But it's a leaky abstraction, NULL is actually 0 literal and could end up being misused easily:
if (some_ptr != NULL) {}
C++11 has nullptr which is now the preferred method as it is explicit and accurate, just be careful about accidental assignment:
if (some_ptr != nullptr) {}
Until you are able to migrate to C++0x I would argue it's a waste of time worrying about which of these methods you use, they are all insufficient which is why nullptr was invented (along with generic programming issues which came up with perfect forwarding.) The most important thing is to maintain consistency.
In C
C is a different beast.
In C NULL can be defined as 0 or as ((void *)0), C99 allows for implementation defined null pointer constants. So it actually comes down to the implementation's definition of NULL and you will have to inspect it in your standard library.
Macros are very common and in general they are used a lot to make up for deficiencies in generic programming support in the language and other things as well. The language is much simpler and reliance on the preprocessor more common.
From this perspective I'd probably recommend using the NULL macro definition in C.
I use if (ptr), but this is completely not worth arguing about.
I like my way because it's concise, though others say == NULL makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.
I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)
Note in C++0x, we can do if (ptr == nullptr), which to me does read nicer. (Again, I hate the macro. But nullptr is nice.) I still do if (ptr), though, just because it's what I'm used to.
Frankly, I don't see why it matters. Either one is quite clear and anyone moderately experienced with C or C++ should understand both. One comment, though:
If you plan to recognize the error and not continue executing the function (i.e., you are going to throw an exception or return an error code immediately), you should make it a guard clause:
int f(void* p)
{
if (!p) { return -1; }
// p is not null
return 0;
}
This way, you avoid "arrow code."
Personally I've always used if (ptr == NULL) because it makes my intent explicit, but at this point it's just a habit.
Using = in place of == will be caught by any competent compiler with the correct warning settings.
The important point is to pick a consistent style for your group and stick to it. No matter which way you go, you'll eventually get used to it, and the loss of friction when working in other people's code will be welcome.
Just one more point in favor of the foo == NULL practice:
If foo is, say, an int * or a bool *, then the if (foo) check can accidentally be interpreted by a reader as testing the value of the pointee, i.e. as if (*foo). The NULL comparison here is a reminder that we're talking about a pointer.
But I suppose a good naming convention makes this argument moot.
The C Programming Language (K&R) would have you check for null == ptr to avoid an accidental assignment.
Actually, I use both variants.
There are situations, where you first check for the validity of a pointer, and if it is NULL, you just return/exit out of a function. (I know this can lead to the discussion "should a function have only one exit point")
Most of the time, you check the pointer, then do what you want and then resolve the error case. The result can be the ugly x-times indented code with multiple if's.
If style and format are going to be part of your reviews, there should be an agreed upon style guide to measure against. If there is one, do what the style guide says. If there's not one, details like this should be left as they are written. It's a waste of time and energy, and distracts from what code reviews really ought to be uncovering. Seriously, without a style guide I would push to NOT change code like this as a matter of principle, even when it doesn't use the convention I prefer.
And not that it matters, but my personal preference is if (ptr). The meaning is more immediately obvious to me than even if (ptr == NULL).
Maybe he's trying to say that it's better to handle error conditions before the happy path? In that case I still don't agree with the reviewer. I don't know that there's an accepted convention for this, but in my opinion the most "normal" condition ought to come first in any if statement. That way I've got less digging to do to figure out what the function is all about and how it works.
The exception to this is if the error causes me to bail from the function, or I can recover from it before moving on. In those cases, I do handle the error first:
if (error_condition)
bail_or_fix();
return if not fixed;
// If I'm still here, I'm on the happy path
By dealing with the unusual condition up front, I can take care of it and then forget about it. But if I can't get back on the happy path by handling it up front, then it should be handled after the main case because it makes the code more understandable. In my opinion.
But if it's not in a style guide then it's just my opinion, and your opinion is just as valid. Either standardize or don't. Don't let a reviewer pseudo-standardize just because he's got an opinion.
This is one of the fundamentals of both languages that pointers evaluate to a type and value that can be used as a control expression, bool in C++ and int in C. Just use it.
I'm a huge fan of the fact that C/C++ doesn't check types in the boolean conditions in if, for and while statements. I always use the following:
if (ptr)
if (!ptr)
even on integers or other type that converts to bool:
while(i--)
{
// Something to do i times
}
while(cin >> a >> b)
{
// Do something while you've input
}
Coding in this style is more readable and clearer to me. Just my personal opinion.
Recently, while working on OKI 431 microcontroller, I've noticed that the following:
unsigned char chx;
if (chx) // ...
is more efficient than
if (chx == 1) // ...
because in later case the compiler has to compare the value of chx to 1. Where chx is just a true/false flag.
Pointers are not booleans
Modern C/C++ compilers emit a warning when you write if (foo = bar) by accident.
Therefore I prefer
if (foo == NULL)
{
// null case
}
else
{
// non null case
}
or
if (foo != NULL)
{
// non null case
}
else
{
// null case
}
However, if I were writing a set of style guidelines I would not be putting things like this in it, I would be putting things like:
Make sure you do a null check on the pointer.
Most compilers I've used will at least warn on the if assignment without further syntax sugar, so I don't buy that argument. That said, I've used both professionally and have no preference for either. The == NULL is definitely clearer though in my opinion.

Brackets around 0 in "return (0);" statement in 'main' function - what are they for? [duplicate]

This question already has answers here:
When do extra parentheses have an effect, other than on operator precedence?
(2 answers)
Closed 3 years ago.
Usually auto-generated c++ "main" function has at the end
return (0);
or
return (EXIT_SUCCESS);
But why there are parentheses in above statements? Is it related to C language or something?
// EDIT
I know this is correct, but someone put these brackets for a reason. What's the reason?!
They are not required (even in c). I think some people use them to make 'return' look more like a function call, thinking it is more consistent.
Edit: It's likely the generator does this for it's own reasons. It may be safer or easier for it to work this way.
But why there are parentheses in above
statements? Is it related to C
language or something?
No. As far as I can tell, C has never required parentheses for return statements. This appears to have been the case even before the first ANSI C standard.
This is actually a very interesting question, however, as I've seen that style prevalent among certain C programmers.
I think the most likely guess as to why this style came about is because all other branching statements (for, while, if, switch) require parentheses around expressions. People might have been unaware that they could omit the parentheses for return statements or were aware of this but wanted to achieve a more uniform look to their code.
The ternary ?: operator is sort of an exception as it is an operator and doesn't require parentheses around the conditional expression, yet people often write parentheses there as well regardless of whether it's needed. Some might find it serves to 'group' an expression into a single unit visually.
My second best guess is that this style was influenced by other languages popular at the time. However, popular, procedural alternatives at the time like Pascal did not require that syntax either (Pascal did not even have return values in the C sense but only output parameters) so if this is the case, I'm not aware of any particularly language from which this style originated.
[Subjective] I prefer styles that require the least amount of superfluous decoration to the code whether it comes to naming conventions or how to format it or whether to use additional parentheses where unnecessary. I find that any such decoration tends to be a matter of unique personal preference and falling in love with one way of decorating code just means that someday you'll have to deal with a completely different way (unless you work strictly alone, in which case I envy you). [/Subjective]
This is actually a requirement for BSD kernel source file style.
man 9 style says:
Space after keywords (if, while, for, return, switch).
and
Values in return statements should be enclosed in parentheses.
As any valid expression can be passed to return, those brackets can be added if desired. It is like doing this:
int i = (0);
You can nest an expression in as many brackets as you like:
return (((((0)))));
Things changes with the use of decltype(auto) in c++14 to deduce return type. If parentheses are used then returned type is deduced to be a reference:
decltype(auto) foo1() {
int n;
return (n); // parentheses causes return type to be int&
}
decltype(auto) foo2() {
int n;
return n; // no parentheses causes return type to be int
}
template<typename T> struct TD;
int main()
{
// main.cpp:19:22: error: aggregate 'TD<int&()> f1' has incomplete type and cannot be defined TD<decltype(foo1)> f1;
TD<decltype(foo1)> f1;
// main.cpp:20:22: error: aggregate 'TD<int()> f2' has incomplete type and cannot be defined TD<decltype(foo2)> f2;
TD<decltype(foo2)> f2;
}
There's a dumb reason - to make return look more like a function call.
There's a smarter reason - if the code is generated, code generators often "play it safe" by putting parentheses around expressions just so they never have to be concerned about the precedence leaking out.
Just my silly speculation:
#define RETURN(val) { if (val) printf("Main Exit With Error %d\n", val); return val; }
int main(argc, argv)
{
...
RETURN (E_FILENOTFOUND);
}
Those are not required. Maybe they come from the tendency to prefer more brackets to fewer brackets when writing macros.
Since you mention auto-generated code it might happen that the code used for generating macros was written by reusing code for generating macros or by a person who thought that more brackets won't hurt, but fewer brackets can be fatal.
One reason I can see for this:
return (ERROR_SUCCESS);
is that it's expressing the concept that ERROR_SUCCESS is opaque. We all know it's 0L, but we shouldn't have to.
That's a fairly weak reason.
Another is that it's aesthetically pleasing to use parentheses for consistency, another weak reason.
So in other words, I don't use it myself, but wouldn't flip out if someone else did. :)

Exiting from the Middle of an Expression Without Using Exceptions

Solved: I figured out a clean way to do it with setjmp()/longjmp(), requiring only a minimal wrapper like:
int jump(jmp_buf j, int i) { longjmp(j, i); return 0; }
This allows jump() to be used in conditional expressions. So now the code:
if (A == 0) return;
output << "Nonzero.\n";
Is correctly translated to:
return
((A == 0) && jump(caller, 1)),
(output << "Nonzero.\n"),
0;
Where caller is a jmp_buf back to the point of invocation in the calling function. Clean, simple, and efficient to a degree that is far less implementation-defined than exceptions. Thank you for your help!
Is there a way to emulate the use of flow-control constructs in the middle of an expression? Is it possible, in a comma-delimited expression x, y, for y to cause a return?
Edit: I'm working on a compiler for something rather similar to a functional language, and the target language is C++. Everything is an expression in the source language, and the sanest, simplest translation to the destination language leaves as many things expressions as possible. Basically, semicolons in the target language become C++ commas. In-language flow-control constructs have presented no problems thus far; it's only return. I just need a way to prematurely exit a comma-delimited expression, and I'd prefer not to use exceptions unless someone can show me that they don't have excessive overhead in this situation.
The problem of course is that most flow-control constructs are not legal expressions in C++. The only solution I've found so far is something like this:
try {
return
x(), // x();
(1 ? throw Return(0) : 0); // return 0;
} catch (Return& ret) {
return ref.value;
}
The return statement is always there (in the event that a Return construct is not reached), and as such the throw has to be wrapped in ?: to get the compiler to shut up about its void result being used in an expression.
I would really like to avoid using exceptions for flow control, unless in this case it can be shown that no particular overhead is incurred; does throwing an exception cause unwinding or anything here? This code needs to run with reasonable efficiency. I just need a function-level equivalent of exit().
You may want to research cfront, which is a program from the late 80's/early 90's that translated C++ into C (no templates or exceptions back then), because there were few, if any, native C++ compilers.
The way it handled inline functions is very similar to what you are trying to do: lots of trinary (?:) operators, commas, and parentheses. However, it could not convert an inline function with control flow more complex than if/then, e.g. a for or while loop, to an expression, and would have to implement that function as non-inline.
The only way to "prematurely exit a comma-delimited expression" would be with the trinary operator and parentheses. For example:
(
first thing,
second thing,
test expression?
(
next thing if successful,
another thing,
return value
)
:( // How often can you use an emoticon as an operator, anyway?
something to do if unsuccessful,
more cleanup,
return value
)
)
If the compiler doesn't short-circuit the then and else clauses of the trinary operator, you're out of luck.
what for? C++ is imperative language. Expressions there are just expressions. Use functional languages if you want to do everything as expressions/functions.
I get the feeling you just have a functional specification (in terms of pre- and post-conditions, for example) of how the translation process must be performed. Since C++ is not a declarative language, but an imperative one, you have to derive yourself a procedural implementation of that translation process before you start coding. And, as you have already seen, it's not as simple as concatenating all your original expressions using commas.
What you are trying to do is have the C++ compiler do your work for you. This won't work, since C++ is not a declarative language, and its compiler won't dynamically try to interpret what you meant from your specifications. And, if this could work, C++ would have to be just another dynamic declarative language, and you would be probably targeting another static language.
A hint on what could work: Analyze every original expression completely (with its possible side-effects) and only then output code. If your expression is compound (it has sub-expressions), don't output anything until you have analyzed the bigger expression.