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 8 years ago.
Improve this question
In C, we could use ternary like
( a == 4) ? a = b: a = 5;
Someone told me better not using it, how do you think?
The conditional operators is useful for forming expressions. Use it when you need an expression which depends, well, on a condition. Don't use it to make statements. For example, your code could be a statement:
if (a == 4) { a = b; }
else { a = 5; }
Or you could write it with a conditional expression, but idiomatically like this:
a = (a == 4 ? b : 5);
Actually you should write
a = (a == 4) ? b : 5;
And that discussion about ternary ops has always seemed quite sterile to me - a couple of good insights can be found here (TL;DR OP's example:
return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
is probably a case where using the ternary operation is not a good idea, in cases like yours it contributes to readability if you ask me).
That is a bad way to use the ternary operator (there are worse ways, but that one is bad). You should use:
a = (a == 4) ? b : 5;
The difference is that this is clearly an assignment to a and the ternary operator determines the value to assign. In your version, you have to look at the insides of the ternary operator to see that it is assigning to a in both branches. (One of the worse ways of using the ternary operator would be (a == 4) ? a = b : b = 5; assigning to two different variables.)
If you feel the need to write nested ternary operators, then you're probably using it inappropriately, too. Occasionally it will be OK, but not very often.
The ?: operator can be used as a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward.
For example:
time_t t = time(0);
now = localtime( & t );
greeting = "Good" + ((now->tm_hour > 17) ? " evening." : " day.");
copied from: http://msdn.microsoft.com/en-us/library/be21c7hw%28v=vs.94%29.aspx
Related
This question already has answers here:
c++ styleguide: why to have non-lvalues on the left side?
(2 answers)
Closed 4 years ago.
Is there any difference between the following two code snippets?
if(x==4)
{
}
and
if(4 == x)
{
}
If so is there any great impact in performance?
Can there be a difference? Yes; if one of the types involved in the comparison is user-defined, then the writer of that type can make their operator== overload not be commutative.
However, such code should be considered ill-behaved. Users expect equality testing to be commutative. And in C++20, it will be much easier to write a commutative equality test than a non-commutative one.
So while the compiler will not stop you, it is reasonably safe to assume that equality testing will be commutative.
In the most common case (read: "should you not be using an overloaded operator == of yours that would make it different, and should the type of x be comparable to 4") these two snippets have similar performances: both terms are going to be evaluated and then compared.
However there are differences, at least in the approach. For example, should you write by accident:
int x = 2;
if(x = 4) // = instead of ==, typed by mistake
{
stuff();
}
this will compile (you might have warnings, but no error), and at run time, this will put 4 into x at test time. As x won't be equal to zero, the content of the block will be executed: stuff() will be called. So there will be a bug as your intent was not to change x and not to have the content of the block executed.
But if you write this:
int x = 2;
if(4 = x) // = instead of ==, typed by mistake
{
stuff();
}
this code will not compile as 4 is a rvalue that cannot be used at the left part of such an assignment.
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 5 years ago.
Improve this question
Consider the speed of the following examples (please ignore that this example is completely ridiculous):
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
if (a == b) {
return pow(a, 2);
}
return a*b;
}
versus
int multiply(int a, int b) {
if (a == 0 || b == 0) {
return 0;
} else if (a == b) {
return pow(a, 2);
} else {
return a*b;
}
}
Obviously, it's not really necessary here, but when I'm working with complex operations, I find it a lot easier to read when formatted as the latter. Does it take any longer to run in the second configuration? Will I be sacrificing anything?
EDIT: Answering's OP question first, then talking about the general case.
Sepcific-to-your-problem Answer: In your case, since you have the return, under each condition, it will break out of the flow-control. In a general case, chaining them, when necessary, is better.
General Answer: Yes, essentially when you're only using if, your program is checking all the conditions, even if one of them was met.
When doing a chain of if,else-if,else, once one of the conditions is met, all the others, in that chain, will be ignored.
In this particular case, no compiler I'm aware of would fail to
generate the exact same output for both. However, in the general
case:
Write for readability and maintainability
Profile profile profile
Optimize only where you find bottlenecks
Test your optimization using more profiling
The fourth part is important, hardware have many surprising
optimizations builtin, it's not at all intuitive what will
be faster.
This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 7 years ago.
Is it possible to create my own operators like '+' or '/'
Is it possible in C++?
I have already found operator '#' , but I do not know how to do this with another.
You can overload +, - for a given class, so they have custom behavior.
You can define preprocessor macros like #define OP(a,b) ((a))-(b)*(a)) and write code like 3 OP 4.
Other than that, I don't believe there's anything deep you can do in C++ to create your own new tokens or syntax. You can always write your own programming language - many people do - and creating a new operator pretty much means you're writing a new programming language by itself.
With the trivial Google search I found a table identifying 42 C++ operators that can be overloaded, and 4 C++ operators that cannot.
I did not verify this information.
If by create, you mean to define,
You can overload many defult operators for custon types, In fact for all of:
+ - * / % ˆ & | ~ ! = < > += -= *= /= %= ˆ= &= |= << >> >>= <<= == != <= >= && || ++ -- , ->* -> ( ) [ ]
Do do custom things for your classes.
You can also define functions, like float add(...) and define that to do whatever you like
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Currently checking out C++ using this tutorial. It explains what the ! NOT operator is, kind of, but I don't think I fully understand why I'd ever want to use it. Can someone please explain?
The ! operator is useful if you want to check that a condition is not currently satisfied.
Imagine a function that tells you if a particular subsystem of your application was initialized and another function to initialize it:
bool subsystem_is_initialized();
void subsystem_initialize();
You could check that it was initialized and initialize it if it wasn't using the not operator.
if (!subsystem_is_initialized())
subsystem_initialize();
For all practical purposes, it's a shorter way to compare a value to zero, with an explicit suggestion that the affected value is boolean. You don't absolutely need it, but then again, neither do you need multiplications (you can loop over an addition), additions (you can do it with binary logic), or most of binary logic (you can do pretty much anything with NANDs, I've been told, but I haven't researched it myself).
Also keep in mind that, like almost all other C++ operators, it can be overloaded by classes.
A language is not always (in fact as good as never) defined to have the minimal set of features but a set of features that useful. For example, if you had the following code:
if (!test_something())
do_something();
You could also express this as
if (test_something()) {
} else
do_something();
but it would be less easy to read. So, while logical negation can usually be expressed by other constructs of the C++ language, it helps readability to express negation explicitly to indicate your intent.
It's used when you need to flip a true/false in a condition, to increase readability.
e.g.
Compare
// Ensure that the thing is NOT red.
if (thing_is_red() == false)
...
if (!thing_is_red())
...
Okay, you want to divide the sum of two numbers to a third one, so you can do this if the third number is not zero.
#include <iostream>
using namespace std;
int main()
{
int a,b,c,sum;
cin >> a >> b >> c;
sum = a+b;
if (c!=0) //which is equivalent to if(!c)
cout << sum/c;
}
I used an easy example in order to understand it quickly. Is everything okay now? Regards and good luck with your study.
! or the NOT operator is the logical equivalent of a NOT gate.
So, a NOT gate truth table says if x is true, then !x is false. and vice-versa.
Not too difficult if you think of it logically. For example NOT of male is a female, NOT true is false, NOT simple is complex..
The most frequent case is probably with an std::istream:
int i;
std::cin >> i;
if ( ! std::cin ) {
// Something went wrong...
}
Other than that, all sorts of classes have isValid() or
isDone() functions; to iterate using a GoF iterator, for
example:
for ( IteratorType i( init ); ! i.isDone(); i.next() ) {
// Do something with i.element()
}
Map classes often have a contains function, so you might ask
if ( ! myMap.contains( key ) )
You'll also use boolean variables from time to time: for
a linear search where the match condition requires some
complicated evaluation, for example:
bool found = false;
int current = 0;
while ( ! found && current != end ) {
// maybe set found...
}
The tutorial you mention:
NOT: The NOT operator accepts one input. If that input is TRUE, it returns FALSE, and if that input is FALSE, it returns TRUE.
it means NOT operator is unary operator means single operand(not a binary operator)
like && and||` are binary operators and there syntax is:
result = operand1 && operand2
result = operand1 || operand2
Unary is:
result = !operand1
and its result values is revert of operand value id operand1 = True then result would be False and if operand1 = False result is True.
same is written there:
For example, NOT (1) evaluates to 0, and NOT (0) evaluates to 1. NOT (any number but zero) evaluates to 0. In C and C++ NOT is written as !. NOT is evaluated prior to both AND and OR.
in c/c++ 0 is False and
Non 0 is equivalent to True.
there is couple of good examples too!
(1).
!( 1 || 0 )
We know 1 || 0 is 1 means true and application of NOT operator makes it 0 means False:
!( 1 || 0 )
=> ! (1)
=> 0 that is false
Do you notice in this expression we have two operators logical || or and ! NOT operator.
!( 1 || 0 )
^ ^
NOT OR
and notice for OR operator || there is two operands bit single for unary NOT
! operator is used for negation purpose in bool condition checks. There are many places you can use it. Simple example:
if (!existInArray(A, i))
check if i is NOT exist in array.
The point of the ! operator is to make an expression that is false into a true expression. It is most often used as a replacement for == false or == 0. It often makes the expression easier to read:
if (p == NULL || p->next != NULL)
is the same as :
if (!p || p->next)
[Ok, so "easier to read" here is obviously quite subjective].
You have quite a number of answers explaining the NOT operator.
I am not a big fan of the ! operator myself. It is not nearly as visible as it should be (in that, it reverses the meaning of the clause).
For example, despite several years of programming in C++, it still takes me several seconds to parse if ( ! ptr ) as opposed to if ( ptr == NULL ) which instantly conveys me its meaning.
Does if ( ! (i % 2) ) check for even or odd numbers? If you didn't have the answer after your eyes went past the '?', and/or had to review the if condition again, you have just made my case.
Reviewing posts, I agree with some of the posters that the NOT operator has valid uses when applied to bools and function calls. Using ! while processing streams is considered idiomatic.
That said, nearly every programmer I know has been bitten by strcmp. I worked in a shop that has a few #defines such as #define STRCMP_EQUAL 0 etc., and required the check to be written as if ( STRCMP_EQUAL == strcmp(str1, str2) ) which, in my opinion, is orders of magnitude more explicit than if ( ! strcmp(str1, str2) ).
! operator could be used with user defined datatypes(classes and structs in c++).
like every operator(expect . : and ::) !operator could be overloaded. See the following scenario.
//A is empty if memeber size is 0, and no further operations are allowed on other members if
// class is empty.
class A{
int size;
int lot;
int price;
public:
bool operator!()
{
if(lot)
return true;
else
return false;
}
};
A AObj;
//Aobj has size greater than 0
if(!Aobj)
{
//code to Fill or reuse the object.
}
The point of the ! operator is to make an expression that is false into a true expression. It is most often used as a replacement for == false or == 0. It often makes the expression easier to read:
if (p == NULL || p->next != NULL)
is the same as :
if (!p || p->next)
[Ok, so "easier to read" here is obviously quite subjective].
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to check for equals? (0 == i) or (i == 0)
Why does one often see “null != variable” instead of “variable != null” in C#?
Why do some experienced programmers write expressions this way?
What is the meaning of NULL != value in C++?
For example,
int k =5;
if( 5 == k )
{
}
is preferred over
if (k == 5)
{
}
Is it considered only for formatting purpose or is there any reason behind it?
Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:
if (k = 5)
This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k is changed, and the conditional always evaluates to true).
Contrast this with
if (5 = k)
This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.
That said, this style of writing code (assignments within conditionals) is not as prevalent today as it once was. Most modern compilers will flag this as a warning, so it's unlikely to go undetected. Personally I don't like the second form and since the compiler is there to help I don't use it.
If you mistype and write
if (k = 5) // instead of ==
then you likely just introduced a hard to find bug. (Actually, it used to be hard to find. Nowadays, most compilers will flag this as a warning.)
This, however, will result in a compile-time error
if (5 = k)
BTW, this style is called Yoda Conditions :-)
It's to avoid the mistake of
if( k = 5 ) {
}
which would always equal true.
A. Who said it's preferred ?!
the only reason i can think of it's to avoid:
int k =5;
if( 5 = k )//notice one "="
{
}
like this you will get a compilation error, while the other way will work. but I think it's less readable and less preferred.
First of all, most people prefer the second form, since it feels "more natural"; the first form is felt as "reversed", and in fact is often called "Yoda conditional".
The rationale behind using the first form is to avoid accidental assignment when typing = instead of == by error. Since in a conditional you can write any expression, = is allowed, so in case of mistyping the instruction
if(k = 5)
{
}
won't check if k is equal to 5, but will assign 5 to k and, since = returns a reference to its left hand operator, the condition will be evaluated as true and the if body will always be executed.
On the other hand, if you typed = instead of == in the Yoda conditional you would get
if(5 = k)
{
}
which results in a compilation error, since you can't assign anything to a literal (5).
Although they look like a good idea, "Yoda conditionals" are quite weird looking, and, most importantly, almost any good compiler with warnings turned on will warn you anyway if you write an assignment inside a conditional expression, so most people just use the "natural looking" form.
It's because a common typo is typing = instead of ==.