Using C ampersand with or without brackets - c++

Let's have two lines of code:
&car->speed
&(car->speed)
Are these two lines equivalent? Will I get in both cases address to the speed?
If they are equivalents, what is better to choose as coding convention?

Are these two lines equivalent? Will I get in both cases address to the speed?
Yes. -> has higher precedence than that of unary &, therefore &car->speed and &(car->speed) are equivalent.
If they are equivalents, what is better to choose as coding convention?
Go with second as it shows the intended behaviour that you are interested in the address of speed.

This question already asked here several times. Postfix expression operators have higher priority than unary operators. So these two expressions
&car->speed
&(car->speed)
are equivalent.
Or another similar example with other unary operator !
!car->speed
!(car->speed)
As for coding convention I would prefer
&car->speed
and if you want to ampersandify car alone, use this:
( &car )->speed

Related

Ampersand and square brackets priority

I see a lot of programmers using brackets around an expression, e.g. :
&(tab[i]) /* I use `&tab[i]`. */
I think it isn't necessary, because the [] operator has a greater priority than & operator. So, why do they use brackets ?
For sake of clarity. Not everyone has all the operator precedences memorized.
I'd say there are basically two reasons:
The programmer isn't sure about operator precedence and codes defensively
To make absolutely clear for every reader (who may not have the precendence memorized) what is going on
It is indeed not necessary because postfix operators always have higher precedence than unary operators.
The people that use parens in &(tab[i]) use them for the same reason they use it in the expression (8 * 5) / 2.
In a recent question, someone had to decypher code like --p---> x < 0. Just like your code, that code is unambiguous as per C++ parsing rules.
However, humans don't always remember all of these complex rules, so many programmers make it a habit to use parens in situations that might look not totally clear to others (or to themselves). It is documenting the real intention of the code.
This is a Good Thing To Do™
Because they find it clearer? Especially for something like this:
int *a[];
Is that a pointer to an array of ints or an array of pointers to int?

Do you know a mental device or trick to learn operator precedence and associativity?

This came up in a conversation with a friend of my nephew who is home from uni. Personally beside the most frequently used ones I never found it all that important and just use parenthesis. But I don't have to take his exam. Anything clever out there?
Edit Well, a rare moment of near unanimity on SO! If only professors listened.
I know this probably doesn't help you in the context of your exam, but I'll answer the question for anyone else who might stumble upon this:
Don't try to memorize operator precedence, beyond the "common cases" e.g. arithmetic. If your statement is unclear, either split it into multiple statements or toss in parenthesis.
Given that there are 16 levels of precedence, I don't think there's an easy trick to memorizing them (no "Roy G Biv" or other mnemonic that I know of).
IMO, the important ones to remember are postfix > unary (i.e., *p++ == *(p++)), unary > arithmetic (~a+b == (~a)+b), bitwise > logical (a|b&&c == (a|b)&&c)), and that conditional, assignment, and comma operators make up the bottom 3 in that order (a=b,c == (a=b),c).
This is why reference manuals were invented. That doesn't help during an exam, of course.
What I do to remember operator precedence (other than arithmetic, which works the same as arithmetic on paper) is that the unary operator always has precedence. Beyond that, I look it up and use parenthesis, as Steven suggests.

Why does postfix operator++ have higher precedence than prefix operator++?

Defined this way, we can do neither ++x++ nor ++x--. But on the other hand, both (++x)++ and (++x)-- are useful expressions: (++x)++ increments x by two and returns the value "in the middle", while (++x)-- is essentially equivalent to x+1 but completely avoids having to call operator+, which can be quite useful sometimes.
So why is the precedence not defined to have ++x++ automatically expand to (++x)++ rather than ++(x++)? Is there some hidden meaning to the latter which I don't understand, or is it just to keep the precedence a simple list with all prefix operators making up one single level?
EDIT Ok, I didn't explicitly say it, but: of course I meant x to be user-defined type. For built-in types, (x+=2)-1 is of course better than (++x)++, and x+1 is a lot better than (++x)--. The situation that I have in mind is an iterator to a rather complicated type of semi-associative container, where operators += and + (being designed for random access) have to rebuild a cache in order to work efficiently for general requests, and are therefore an order of magnitude slower than ++. But of course I can modify them to always check first if the argument is a very small integer, and in that case just call operator++ repeatedly instead of doing the random-access procedure. That should work fine here, though I could imagine I might at some point have a situation in which I want operator+= to always go the random-access way, regardless of how small numbers I present it.
So... for me, I would conclude the answer to be:
the advantage of having a simple and well-memorizeable precedence list in which all postfix operators come before any of the prefix operators is sufficient to tolerate the minor drawback of always having to use parentheses to compose pre- and postfix operators ++/--, as this composition is used very seldom.
The simpler "C does it this way", while it seems likely to be the real reason, is far less satisfying in to me, because since ++x++ was not allowed at all in C it would have been possible to redefine this very composition without damaging any existing code.
Anyway, I will go on using (++x)--, as the parentheses really do not hurt so much.
(++x)++ increments x by two and returns the value "in the middle"
Why not (x += 2) - 1 or (++x, x++)? Both seem to be clearer. For scalars, both are well-defined also in C++03, as opposed to your proposed expression.
(++x)-- is essentially equivalent to x+1 but completely avoids having to call operator+, which can be quite useful sometimes.
That's an arbitrary statement without any explanation. So I'm going to throw into the pool:
x+1 is essentially equivalent to (++x)-- but completely avoids having to call operator++ and operator-- which can be useful sometimes.
So why is the precedence not defined to have ++x++ automatically expand to (++x)++ rather than ++(x++)
Just to make such arcane corner cases not error out? No way. Can you please recite man operator for me? If you cannot do that, better not try and write ++x++ in your code.
C++ standard just kept the C rules and obviously those weren't fixed considering operator overloading and idioms yet be invented in a yet to be invented language.
Looking at what is available in D.M. Ritchie Home Page, on see that this precedence is already present in B (Unary operators are bound right to left. Thus -!x++ is bound -(!(x++)) in Users' Reference to B) and I didn't see increment operators in BCPL.
Both (++x)++ and (++x)-- invoke undefined behaviour [assuming x to be a primitive type]. For user defined type the scenario would be different. However it is not generally recommended to use such confusing expressions in your code.
As far as the precendence is concerned this answer explains why post increment has higher precedence than pre increment.

Why "**" does not bind more tightly than negation in OCaml?

after this question, I don't know what to think.
In OCaml, if you do something like -1.0**2.0 (because of the typing you need to have float), you obtain 1.00. According to the standard order of operations, the result should be -1 (as in python).
I wasn't able to find the reason or a clear definition of the operator precedence in OCaml...
Is this because of the type system ? or the fact that there's a binding underneath with pow ?
As the very page you quote says, "The order in which the unary operator − (usually read "minus") acts is often problematical." -- it quotes Excel and bc as having the same priority for it as O'CAML, but also says "In written or printed mathematics" it works as in Python. So, essentially, there's no universal consensus on this specific issue.
Operator precedence is syntax-directed in OCaml, which means that the first character of the function identifier (and whether it's unary or binary) determines the operator precedence according to a fixed sequence. Contrast this with languages like Haskell, where the operator precedence can be specified at function definition regardless of which characters are used to form the function identifier.

Priority of C++ operators "&" and "->"

Given the following:
&row->count
Would &(row->count) be evaluated or (&row)->count be evaluated in C++?
EDIT: Here's a great link for C++ precedence.
As far as precedence rules go, I've always liked the one put forth by Steve Oualline in "Practical C":
There are fifteen precedence rules in
C (&& comes before || comes before
?:). The practical programmer reduces
these to two:
1) Multiplication and division come
before addition and subtraction.
2) Put parentheses around everything
else.
&(row->count)
This is already asked. But here is a link.
Edit:
Ok this question is very similar. And possibly there is an other one.
May I suggest that you resolve such questions using a test programme? That has the advantage that you will know for sure that the answer is correct for your implementation, and you are not exposed to the risk of badly answered questions.
C operator precendence is explained here
As per the table, -> is higher priority than the & operator, so it's &(row->count)
&(row->count)
-> has a higher priority than & (address of). So your expression would be evalutated as &(row->count)