It appears that in Game Maker 8, 8.1, and Studio (at least) that the assignment operator = is identical to the comparison operator ==. For example, these lines do the same thing:
if (a=b) {}
if (a==b) {}
Is this function meant to be friendly to new users? Should I continue using == or switch to =? Or does it make no difference?
P.S. Things like incrementing still work with = similarly to ==:
if a=b++{} //b is still incremented, but a does not change
This functionality was left over from previous versions as stated in the GameMaker help file.
"However, this is a legacy from old GameMaker versions and you should use the == operators for comparing and = for assigning."
It would be good practice for you to use == when comparing as that is what it is designed for. Also, if you were to move onto another languages like PHP, using the = operator would actually initialize the variable in the if statement. This could give you quite a headache if you are in the habit of using the single = operator.
Related
Still getting used to the formatting when writing C++ code, come from a Lua background.
How do I correctly format a if/conditional expressions as my example highlights below.
This will correctly run, but with warnings which is unideal:
return (boolean == true) and init() or 0;
Highlighted Warning:
expected a ';'C/C++ (between "(boolean == true)" "and")
and and or are keywords are considered a bit archaic. They are technically valid C++ keywords in modern C++ (since C++98 it seems). You must be using a very old C++ compiler that was written before they were added to C++. They, and their usage, never took off. Classical && and || operators continue to rule the roost and are not going anywhere.
Therefore: although it is true that this expression should be logically equivalent to boolean && init(), you might want to consider assigning somewhat higher priority of updating your C++ compiler to something more modern, if that's indeed the reason for the compilation error.
Recently I found a code where is used the keyword and which working like &&. So are they both the same or is there any specific condition to use it?
The C++ standard permits the token && to be used interchangeably with the token and.
Not all compilers implement this correctly (some don't bother at all; others require the inclusion of a special header). As such, code using and can be considered idiosyncratic.
The fact that the equivalence is at the token, rather than the operator, level means that since C++11 (where the language acquired the rvalue reference notation), you can arrange things (without recourse to the preprocessor) such that the statement
int and _int(string and vector);
is a valid function prototype. (It's eqivalent to int&& _int(string&& vector).)
As can be seen here, they're the same thing.
No difference. and is just an alternative name for &&.
See https://en.cppreference.com/w/cpp/keyword/and.
There is nothing different in and and &&
The and operator is an alternative representation of the && operator (binary or logical AND).
you can see the complete article here -
http://docwiki.embarcadero.com/RADStudio/Sydney/en/And
What is the difference between "and" and "&&" in c++
The main difference is that and doesn't use the character &.
Otherwise, there is no difference.
is there any specific condition to use it?
Along with other alternative tokens such as the digraphs, it exists in order to allow writing programs on exotic systems with character encoding (such as BCD or ISO 646) that don't have the special symbols such as &.
Unless you're writing on such system where it's necessary to use alternative tokens, you conventionally shouldn't be using them.
They and operator si they name of the &&
The and operator is an alternate to the && operator.
So I recently installed CLion and after some setup I started messing with some older code I'd written. Now a great thing about CLion is that it helps you with coding style etc. but one thing I found strange is that it recommended to me to split the definition and assignment of variables. I remember a specific case where I defined strings as follows:
string path = "mypath";
But the IDE recommended to write it like:
string path;
path = "mypath";
Now I started looking for this online to find pros and cons of both methods. Apparently the former is faster but the latter is more secure because it calls the copy constructor or something (I didn't quite understand that part). My question is basically: Since CLion recommends doing it the latter way, does that mean that it is always better? Is there one way that is preferred over the other or is it situational? Do they each have their pros/cons and if so, what are they?
Any help or reliable resources are greatly appreciated.
Thanks in advance,
Xentro
Your IDE needs to be consigned to the bin.
string path = "mypath"; is an infinitely better pattern. This is because, in general, there is no potential hazard of an indeterminate value of path. (Granted, in this case, that is not an issue since a std::string has a well-defined default constructor but the preferred way is a good habit to get into).
The compiler is also spared the headache of constructing then assigning a value to an object.
But the IDE recommended to write it like:
string path;
path = "mypath";
Time to uninstall the IDE. The recommendation is utter nonsense.
Perhaps the worst thing about it is how it prevents const correctness. If path never changes, then you should make it const, and you can only do that if you initialise the variable with the correct value right away:
std::string const path = "mypath";
Note that depending on the context of the code, you may also want to use auto (which will turn the variable into a char pointer, because the deduced type of "mypath" is a char array, but perhaps it turns out you don't even need a full-fletched std::string?) - and that also only works if you do not follow the stupid IDE recommendation:
auto const path = "mypath";
Apparently the former is faster
Nonsense. This is not about speed but about correctness and code maintainability.
but the latter is more secure because it calls the copy constructor or something (I didn't quite understand that part).
That's nonsense, too. It calls one of std::string's overloaded assignment operators, not the copy constructor. And it's not more "secure" in any usual sense of the word.
The advice is nonsense and other answers here tell that already.
I want to add a source for this: Straight from the creator of C++ Bjarne Stroustrup and the chairman on C++ comete (hope I don't get his postion wrong) Herb Sutter:
C++ core guidelines:
ES.20: Always initialize an object
Reason Avoid used-before-set errors
and their associated undefined behavior. Avoid problems with
comprehension of complex initialization. Simplify refactoring. Example
void use(int arg)
{
int i; // bad: uninitialized variable
// ...
i = 7; // initialize i
}
No, i = 7 does not initialize i; it assigns to it. Also, i can be read
in the ... part. Better:
void use(int arg) // OK
{
int i = 7; // OK: initialized
string s; // OK: default initialized
// ...
}
Note The always initialize rule is deliberately stronger than the an object must be set before used language rule. The latter, more
relaxed rule, catches the technical bugs, but:
It leads to less readable code
It encourages people to declare names in greater than necessary scopes
It leads to harder to read code
It leads to logic bugs by encouraging complex code
It hampers refactoring
The always initialize rule is a style rule aimed to improve
maintainability as well as a rule protecting against used-before-set
errors.
string path = "mypath";
The code above is called using a copy constructor
string path;
path = "mypath";
And the other one is called uses the assignment operator.
Theoretically, the pros and cons really depend on how the compiler going to deal with the code. So it vary from compiler to compiler. In general, the first way is trying to build a object by copying another existing object. While the second one is first create a new empty object, then using the assignment operator ("=", the equal mark) to give value to the variable.
You can see more discussions in the following links:
Why separate variable definition and initialization in C++?
and What's the difference between assignment operator and copy constructor?
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.
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.