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 10 years ago.
I've recently seen this question. Which contained (what I believe is) a very common early programer mistake of writing if(x==10 || 12) when you mean if(x==10 || x==12) which made me wonder. Why (to my knowledge) there is no support for this if(x==10 || 12) seemingly more natural syntax, or at least some similar syntax. So my questions are:
1) Is there some kind of syntactic sugar/macro expansion/shorthand for this kind of expression in any of the more common languages (c,c++,java,c#). If not, why not ?
2) Is there a way using java and eclipse to add this (as a compiler macro expansion or any other useable solution) ?
EDIT: clarification, I did not mean I wish to alter the meaning of if(x==10 || 12). I was looking for syntactic sugar that is shorter than if(x==10 || x==12) but is functionally equivalent.
That's because it's makes more sense for if (x == 10 || 12) to be interpreted exactly as it's written. That's "If x equals to 10, or 12 is truthy". If you want something done, write it explicitly.
You could use a switch case with butted up case statements in C#. You can't mess too much with ifs as you would break more legitimate cases and reduce readability. It would be syntactic salt rather than sugar.
You can use array or set lookup in languages that support compact representation of arrays or sets.
Javascript (as well as PHP and Java) has array literals:
if( [10,12].indexOf(x) != -1) ...
you can also use the bitwise negation as a shortcut for !=-1:
if(~[10,12].indexOf(x)) ...
Php 5.4 has array literals as well, and you can use them without a temp variable from 5.5 (I think). This should be superlinear as well, but generates notices unless you use # or in_array:
if(#[10=>true, 12=>true][$x]) ...
A regex lookup is also an option in languages that support compact regex syntax and you're matching strings. This has the benefit of being potentially faster than array search:
if(/^(10|12)$/.test(x)) ...
A switch has also been suggested:
switch(x){
case 10:
case 12:
...
}
If that was allowed, how would you write a condition like this one:
if( x == a || b )
where x and a are chars or integers and b can be either true or false?
For example:
x = 'a';
b = true;
// later in the program
if( x == 'c' || b )
Related
A question was posted about chained comparison operators and how they are interpreted in different languages.
Chaining comparison operators means that (x < y < z) would be interpreted as ((x < y) && (y < z)) instead of as ((x < y) < z).
The comments on that question show that Python, Perl 6, and Mathematica support chaining comparison operators, but what other languages support this feature and why is it not more common?
A quick look at the Python documentation shows that this feature has been since at least 1996. Is there a reason more languages have not added this syntax?
A statically typed language would have problems with type conversion, but are there other reasons this is not more common?
It should be more common, but I suspect it is not because it makes parsing languages more complex.
Benefits:
Upholds the principle of least surprise
Reads like math is taught
Reduces cognitive load (see previous 2 points)
Drawbacks:
Grammar is more complex for the language
Special case syntactic sugar
As to why not, my guesses are:
Language author(s) didn't think of it
Is on the 'nice to have' list
Was decided that it wasn't useful enough to justify implementing
The benefit is too small to justify complicating the language.
You don't need it that often, and it is easy to get the same effect cleanly with a few characters more.
Scheme (and probably most other Lisp family languages) supports multiple comparison efficiently within its grammar:
(< x y z)
This can be considered an ordinary function application of the < function with three arguments. See 6.2.5 Numerical Operations in the specification.
Clojure supports chained comparison too.
Chained comparison is a feature of BCPL, since the late 1960s.
I think ICON is the original language to have this, and in ICON it falls out of the way that booleans are handled as special 'fail' tags with all other values being treated as true.
This question already has answers here:
Is it okay to use "and", "or" etc. instead of "&&", "||"?
(9 answers)
Are "not, and, or, not_eq.." part of the C++ standard? (And why might they be used or avoided in code?)
(5 answers)
Closed 5 years ago.
I saw alternative operators (like and, or, not etc.) when browsing cppreference.
They are alternatives to "normal" operators like &&, ||, ! etc.
I examined the assembly for code that uses && and and. Both versions generated the same assembly.
Code :
#include <iostream>
int n = 1;
int main()
{
// if(n > 0 && n < 5)
if(n > 0 and n < 5)
{
std::cout << "n is small and positive\n";
}
}
So my questions are:
What is the difference between the && and and operators?
Where and when do I use and over &&?
If there is no difference, then why does C++ introduce alternative operators (like and, or, not etc.)?
What is the difference between the && and and operators?
There is none1. The "alternative" aspect of these operators means that they can be used to construct the exact same expressions from a semantic perspective.
Where and when do I use and over &&?
This is largely a matter of preference. I'm too used to && to not use it, but can understand if someone finds and more readable.
why does C++ introduce alternative operators?
C++ was designed to be available on a variety of character sets and platforms. Trigraphs, like Bathsheba pointed out, are another example of such a feature. If a character set would not allow && to be written (say, because it simply didn't have the & character) then one can still get by with the alternative representation. Nowadays, it's largely moot.
1 Actually, upon further thinking, my answer to your first question can be refined. There is a slight lack of equivalence, pertaining to how tokens are parsed. && doesn't require a space to be parsed as a separate token, while and does. That means:
void foo(bool b1, bool b2) {
if(b1&&b2) { // Well formed
}
if(b1andb2) { // ill formed, needs spaces around `and`
}
}
and, or, not, &c. are examples of the alternative operators.
For the full list see http://en.cppreference.com/w/cpp/language/operator_alternative; the opening paragraph is a raison d'etre:
C++ (and C) source code may be written in any non-ASCII 7-bit
character set that includes the ISO 646:1983 invariant character set.
However, several C++ operators and punctuators require characters that
are outside of the ISO 646 codeset: {, }, [, ], #, \, ^, |, ~. To be
able to use character encodings where some or all of these symbols do
not exist (such as the German DIN 66003), C++ defines the following
alternatives composed of ISO 646 compatible characters.
If I were you I'd shy away from using them, much in the same way as you ought to shy away from using digraphs and trigraphs, even if the latter make for interview fun.
Trigraphs for example are explicitly discontinued from C++17. You might see and &c. being dropped in future standards too.
This question already has answers here:
How can I check whether multiple variables are equal to the same value?
(3 answers)
Closed 7 years ago.
I am a newbie to programming in C++ and I have a question regarding if conditions. We are currently learning C++ at school(Using TC, i know it's an old compiler,but yeah). I am currently making a tic-tac-toe program, an undefeatable one. Now, this is my problem.
I want to check the equality of 3 variables, and run the if body only if the 3 variables are not equal to another variable.
Why is this set of code not working?
if(a==b==c!=d)
{
}
Adding parentheses doesn't help, I'm probably doing it wrong.(Please excuse my ignorance)
if((a==b==c)!=d)
{
}
Thanks in advance!
-CaptainAwesome
You have to write each condition individually and combine them using && (logical and):
if(a==b && b==c && c!=d)
{
// ...
}
Because you made this up. You can't do boolean comparisons like this.
Stick to two operands at a time and use && and || to combine results.
I'm not entirely clear on your requirements but start with something like this:
if (a == b && b == c && c != d)
This question already has answers here:
What is the difference between if(CONST==variable) or if(variable==CONST)?
(5 answers)
Closed 9 years ago.
I've come across some code that flips how a condition is checked and was wondering why this would be done aside from a weird personal quirk. I've never seen any text books use it nor have I seen any sample code done this way.
// why do it this way?
if (5 == myValue)
{
// do something
}
// instead of:
if (myValue == 5)
{
// do something
}
I've only seen this way for == operand but not for any other operands.
Some people like doing that because if you mess up and type a single-equals instead of a double-equals, "if (val = 5)" is only a compiler warning, while "if (5 = val)" is an error (you can't assign to a constant).
I think it's sort of ugly, personally, and that you should be checking your warnings just as much as your errors, but that is the reason for that convention (which is thankfully not universal, but is at least moderately widespread. It is also true that it might not universally have been treated as even a warning by much older compilers, and this convention has been around for a long time.)
Fun fact: I was just reading Code Complete (Second Edition), and Steve McConnell agrees with me, stating his personal preference is "to use number-line ordering and let the compiler warn me about unintended assignments". Steve McConnell by definition knows what he's talking about.
Some folks do it for readability when myValue is deemed less interesting than 5; it puts the constant value in a more prominent place. There is no practical reason for it - purely a judgment call on the part of the coder.
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 10 years ago.
In the language I was first introduced to, there was a function repeat(), that took a string, and repeated it n times. For example, repeat ("hi", 3) gives a result of "hihihi".
I did have quite a few times that I used this function, but to my dismay, I've never found something similar in C++. Yes, I can easily make my own, or make it easier to use, but I'm kind of surprised that it isn't included already.
One place it would fit in really well is in std::string:
std::string operator* (const std::string &text, int repeatCount);
std::string operator* (int repeatCount, const std::string &text);
That would allow for syntax such as:
cout << "Repeating \"Hi\" three times gives us \"" << std::string("Hi") * 3 << "\"."
Now that in itself isn't all too great yet, but it could be better, which brings me to my other part: literals.
Any time we use the string operators, such as operator+, we have to make sure one argument is actually a string. Why didn't they just define a literal for it, like ""s? Literal suffixes not beginning with an underscore are reserved for the implementation, so this shouldn't conflict seeing as how this could have been added before anyone actually started making their own.
Coming back to the repeat example, the syntax would simply be:
cout << "123"s * 3 + "456"s;
This would produce:
123123123456
While at it, one for characters could be included as well, to satisfy cout << '1's + '2's;
Why weren't these two features included? They definitely have a clear meaning, and make coding easier, while still using the standard libraries.
Well, as for the multiplication, it's not really in C++'s philosophy: languages like Ruby come "batteries included" and with the "principle of least surprise". They are intended to have lots of these little niceties as an above-and-beyond-the-minimum feature. C++ is a system level language which is intended to be "closer to the metal", which is abundantly clear in that a string isn't even a core data type of the language, but a library-provided addon. Even FORTRAN has a native string type, so you can see how low-level C++ is positioned to be. This is intentional: what if you're programming an embedded chip with 1K storage and have no use for strings? Just don't include 'em.
Anyway, it's not 100% clear what the multiplication operator is supposed to do. In other words, in the core language and libraries of C++, no feature gets in unless it seems that almost everyone would agree on the proposed functionality. It's got to be really universal.
I for one might think that "123" * 3 could give "369" - multiply any digits by 3. I further propose that this interpretation is "sane" enough to keep your repeat operator interpretation from being the only unambiguous interpretation.
The literal notation is far easier and more clear to answer: std::string is a part of the standard library, which is one level of abstraction above the language syntax itself. In other words, the literal notation would bust through the level of abstraction that separates "language features" and "the library that you can expect to be bundled with your compiler".
std::string.append(numtimes, char to repeat); There. It does. Now, that works for character literals, as for doing that with strings there is no way to do that declaratively. Also to note, the std::string class isn't a language type, a string litteral in c++ is const char *. A pointer. Which Arrays decay into pointers, and that's how the std::string class treats what it contains , an array of characters ie char, or wchar_t for std::wstring. there templated on those types.