What happen first, casting or shifting bits [C++] - c++

What's happening first here in C++, shift or casting?
(dword)header[2]<<8

From here Operator precedence you can see that bitwise shift has lower precedence than type cast. So that is equivalent to:
((dword) (header[2])) << 8
Always use parentheses for things that are not clear, even if you check that it is actually ok, because it improves code readability. (you might not want to enclose the subscript like I did to emphasis all the precedences here, but use the other parenthesis).

Related

Using C ampersand with or without brackets

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

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.

What does it mean when an array name is in parentheses with a caret pointer before it?

I have an array of unsigned numbers, called dataArray (actually in the program I am trying to figure out, they are entered as hexadecimal numbers, but I don't think that's important). I have another variable of type unsigned char, called c.
What does this do?
unsigned int dataArray[]={1,2,3,4,5};
unsigned char c;
x=c^ (dataArray)[i];
I have read that the caret is a reference to c, but what does it mean when the array name is in parentheses? It seems that x is just set to the (i-1)th element in dataArray, but under what conditions is that not so?
Thanks.
The parenthesis don't impact the semantics here. x is computed as the bitwise exclusive-or of c (undefined here) and dataArray[i].
In some derived language, the caret is used to declare a managed pointer. It's the so-called C++/CLI language made by microsoft and is used in .Net. It doesn't have that meaning in normal C++. In expressions, the caret means, as already explained by others, the bit-wise XOR, anyway.
The ^ character as it is used here is a bitwise XOR (see wikipedia). The parentheses don't to anything here, as the operator [] has higher precedence than bitwise-xor.
If this is really C++, then the '^' is the XOR bitwise operator. The parentheses are extra and do nothing in this example.
The ^ is not overloaded, as far as I know. If it is entered and compiles properly, it is going to attempt a XOR operation, though in this case it's probably going to be messing with data you don't want it to...
Ok, cool. That makes sense in the program I'm using. I had thought the caret was a pointer, but it's an XOR and then later on in the line there's an & (bitwise AND). The program is for sending and receiving signals from electronics, so bit-level logic is to be expected. Thanks very much for the fast replies.