operators
Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5;
long j = 8;
Then i = i + j;
will not compile but i += j;
will compile fine.
Does it mean that in fact i += j;
is a shortcut for something like this
i = (type of i) (i + j)
?
I found this code in a RailsCast:
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
What does the (&:name)
in map(&:name)
mean?
What does the following code mean in Ruby?
||=
Does it have any meaning or reason for the syntax?
Why are there no ++ and -- operators in Python?Why are there no ++
and --
operators in Python?
This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list.
It used to be hard to find questions about operators and other syntax tokens.¹
The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them, not to copy over content from the PHP Manual.
Note: Since January 2013, Stack Overflow does support special characters. Just surround the search terms by quotes, e.g. [php] "==" vs "==="
If you have been pointed here by someone because you have asked such a question, please find the particular syntax below. The linked pages to the PHP manual along with the linked questions will likely answer your question then. If so, you are encouraged to upvote the answer. This list is not meant as a substitute for the help others provided.
If your particular token is not listed below, you might find it in the List of Parser Tokens.
&
Bitwise Operators or References
=&
References
Double question mark
??
Null Coalesce Operator (since PHP 7)
Question mark followed by a type declaration
?string
?int
?array
?bool
?float
Nullable type declaration (since PHP 7.1)
?->
question mark followed by object operator is a NullSafe Operator (since PHP 8.0)
:
Alternative syntax for control structures, Ternary Operator, Return Type Declaration
=>
Arrays
<=>
Comparison Operators (since PHP 7.0)
+
Arithmetic Operators, Array Operators
+=
and -=
Assignment Operators
++
and --
Incrementing/Decrementing Operators
<?=
Short Open Tags
[]
Arrays (short syntax since PHP 5.4)
$var = []
empty array..
Double-dot character range
...
Argument unpacking (since PHP 5.6)
**
Exponentiation (since PHP 5.6)
#
One-line shell-style comment
#[]
Attributes (since PHP 8)
I have seen uses of @
in front of certain functions, like the following:
$fileHandle = @fopen($fileName, $writeAttributes);
What is the use of this symbol?
What is Ruby's double-colon `::`?What is this double-colon ::
? E.g. Foo::Bar
.
I found a definition:
The
::
is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.
What good is scope (private, protected) if you can just use ::
to expose anything?
Note: The answers were given in a specific order, but since many users sort answers according to votes, rather than the time they were given, here's an index of the answers in the order in which they make the most sense:
(Note: This is meant to be an entry to Stack Overflow's C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started in the first place, so your answer is very likely to get read by those who came up with the idea.)
"is" operator behaves unexpectedly with integersWhy does the following behave unexpectedly in Python?
>>> a = 256
>>> b = 256
>>> a is b
True # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False # What happened here? Why is this False?
>>> 257 is 257
True # Yet the literal numbers compare properly
I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.
Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the is
operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?
Is there a ternary conditional operator in Python?
What do all of Scala's symbolic operators mean?Scala syntax has a lot of symbols. Since these kinds of names are difficult to find using search engines, a comprehensive list of them would be helpful.
What are all of the symbols in Scala, and what does each of them do?
In particular, I'd like to know about ->
, ||=
, ++=
, <=
, _._
, ::
, and :+=
.
Is there a null coalescing operator in Javascript?
For example, in C#, I can do this:
String someString = null;
var whatIWant = someString ?? "Cookies!";
The best approximation I can figure out for Javascript is using the conditional operator:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
Which is sorta icky IMHO. Can I do better?
Is there a conditional ternary operator in VB.NET?In Perl (and other languages) a conditional ternary operator can be expressed like this:
my $foo = $bar == $buz ? $cat : $dog;
Is there a similar operator in VB.NET?
Can't operator == be applied to generic types in C#?According to the documentation of the ==
operator in MSDN,
For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types.
So why does this code snippet fail to compile?
bool Compare<T>(T x, T y) { return x == y; }
I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the ==
operator is predefined for all types?
Edit: Thanks, everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct.
But, in case I'm using a reference type, would the ==
operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?
Edit 2: Through trial and error, we learned that the ==
operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true
, even when Test.test<B>(new B(), new B())
is called:
class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }
Difference between >>> and >>
What is the difference between >>>
and >>
operators in Java?
How do I use pre-increment/decrement operators (++
, --
), just like in C++?
Why does ++count
run, but not change the value of the variable?
I have the following code:
public class Tests {
public static void main(String[] args) throws Exception {
int x = 0;
while(x<3) {
x = x++;
System.out.println(x);
}
}
}
We know he should have writen just x++
or x=x+1
, but on x = x++
it should first attribute x
to itself, and later increment it. Why does x
continue with 0
as value?
--update
Here's the bytecode:
public class Tests extends java.lang.Object{
public Tests();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]) throws java.lang.Exception;
Code:
0: iconst_0
1: istore_1
2: iload_1
3: iconst_3
4: if_icmpge 22
7: iload_1
8: iinc 1, 1
11: istore_1
12: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
15: iload_1
16: invokevirtual #3; //Method java/io/PrintStream.println:(I)V
19: goto 2
22: return
}
I'll read about the instructions to try to understand...
JavaScript plus sign in front of function expressionI’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:
+function(){console.log("Something.")}()
Can someone explain to me what the +
sign in front of the function means/does?
I saw a line of C that looked like this:
!ErrorHasOccured() ??!??! HandleError();
It compiled correctly and seems to run ok. It seems like it's checking if an error has occurred, and if it has, it handles it. But I'm not really sure what it's actually doing or how it's doing it. It does look like the programmer is trying express their feelings about errors.
I have never seen the ??!??!
before in any programming language, and I can't find documentation for it anywhere. (Google doesn't help with search terms like ??!??!
). What does it do and how does the code sample work?
I saw some code that seems to use an operator I don't recognize, in the form of two exclamation points, like so: !!
. Can someone please tell me what this operator does?
The context in which I saw this was,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
What does question mark and dot operator ?. mean in C# 6.0?
With C# 6.0 in the VS2015 preview we have a new operator, ?.
, which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
What is the difference between the | and || or operators?I have always used ||
(two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |
. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:
>>> 6/3
2
>>> 6//3
2
What are bitwise shift (bit-shift) operators and how do they work?
I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...
At a core level, what does bit-shifting (<<
, >>
, >>>
) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.
How would you say "does not equal"?
if hi == hi:
print "hi"
elif hi (does not equal) bye:
print "no hi"
Is there something similar to ==
that means "not equal"?
I bumped into this strange macro code in /usr/include/linux/kernel.h:
/* Force a compilation error if condition is true, but also produce a
result (of value 0 and type size_t), so the expression can be used
e.g. in a structure initializer (or where-ever else comma expressions
aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
What does :-!!
do?
Is there such a thing? It is the first time I encountered a practical need for it, but I don't see one listed in Stroustrup. I intend to write:
// Detect when exactly one of A,B is equal to five.
return (A==5) ^^ (B==5);
But there is no ^^
operator. Can I use the bitwise ^
here and get the right answer (regardless of machine representation of true and false)? I never mix &
and &&
, or |
and ||
, so I hesitate to do that with ^
and ^^
.
I'd be more comfortable writing my own bool XOR(bool,bool)
function instead.
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace ==
(two equals signs) with ===
(three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0
inside of an if
statement.
Is there a performance benefit to replacing ==
with ===
?
Any performance improvement would be welcomed as many comparison operators exist.
If no type conversion takes place, would there be a performance gain over ==
?
After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated
, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4. I would assume this is also valid C since it works in GCC as well.
Here's the code:
#include <stdio.h>
int main()
{
int x = 10;
while (x --> 0) // x goes to 0
{
printf("%d ", x);
}
}
Output:
9 8 7 6 5 4 3 2 1 0
Where is this defined in the standard, and where has it come from?
What's the difference between equal?, eql?, ===, and ==?I am trying to understand the difference between these four methods. I know by default that ==
calls the method equal?
which returns true when both operands refer to exactly the same object.
===
by default also calls ==
which calls equal?
... okay, so if all these three methods are not overridden, then I guess
===
, ==
and equal?
do exactly the same thing?
Now comes eql?
. What does this do (by default)? Does it make a call to the operand's hash/id?
Why does Ruby have so many equality signs? Are they supposed to differ in semantics?
operators