Thursday, July 9, 2009

The address operator &(programming in C)?

the address operator %26amp; cannot be applied to expressions, is this true?

The address operator %26amp;(programming in C)?
I know you cannot have the address of a constant, i.e. %26amp;3 is wrong.





(2 * x + func()) is a valid expression, and %26amp;(2 * x + func()) is invalid...





And I just tried to compile using the pointer to the address of a register, and I got the error "can't take address of object"





So, I like the answer "None of the above."








Also, ctbuckweed's expresion:


%26amp;s[0] = %26amp;s[9] + %26amp;s[10] // expression #2





is not valid. You cannot assign a value to %26amp;s[0]. You cannot modify the address of s[0]. The address of s[0] is basically a constant.


The terms lvalue and rvalue come into play here. Left and Right values. lvalues are variables. x = 3. x is a valid lvalue


3 = x is invalid, 3 is not an lvalue. (x is a valid rvalue) Almost anything is a valid rvalue, lvalue is a little different. %26amp;s[0] is not a valid lvalue..





Make sense?
Reply:yes it can. Is this what you mean?





char s[500];





char *p = %26amp;s[20]; // expression #1 point to the 20th character of s


%26amp;s[0] = %26amp;s[9] + %26amp;s[10] // expression #2
Reply:You're not using the word "expression" in a precise way so your question is vague.





You can't take the address of a literal AFAIK. So %26amp;3 is illegal. OTOH it would be very much like C to honor this syntax and return the address of the literal constant value 3.





Generally if you find yourself wanting to do this, you're thinking of your problem wrong.


No comments:

Post a Comment