Re: Need Explanation on Lvalue Assignment for the following snippet
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Thu, 04 Sep 2008 08:11:49 +0000
Pranav said:
#include<stdio.h>
#include<conio.h>
int main()
{
const int i=6;
int k = 9;
int a[i], *c = a, *v = a ;
a[2] = 9;
*c++ = *v++; // ( 1 ) This line does not generate any exception /
error
Nevertheless, the behaviour of the statement, and therefore the program, is
undefined, because *v++ reads a[0], the value of which is indeterminate.
k++ = k++; // ( 2 ) But this line is generating
This is not only a syntax error (because k++ is not an lvalue) but, even if
it were not a syntax error, it would generate undefined behaviour because
you're modifying (or rather, trying to modify!) a value twice between
consecutive sequence points.
k++ = 6; // ( 3 ) This Also Generating
getch();
}
Now I know that you cannot assign a value to an expression; But why
does the above (1) expression not generating a exception/error/
warning?
Because *c++ IS an lvalue! ++ has precedence over *, so it is the pointer,
not the object pointed to, whose value is incremented. As a side effect,
the old value of the pointer is dereferenced, yielding an object - ie an
lvalue - ie something you can store something in.
and (2) & (3) are generating as they are supposed to. Please
explain this.
Is this due to operator precedence in the case(1),
Yes.
ie the expression
access the value and then assign them and then increment the pointers
and move forward. Correct if I am wrong..,
Your conclusion is correct, but for the wrong reason. This *is* to do with
precedence, but *not* to do with order of evaluation. Precedence is to do
with which operators bind to which operands, not to do with the order in
which operations are carried out.
(I am using DevC++ Compiler for testing)
Make sure you invoke it in C mode, then, because C is a different language
to C++. (If you're using C++, you'd be better off asking in
comp.lang.c++.)
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.
- Prev by Date: Re: detecting ASCII/EBCDIC
- Next by Date: Re: printf
- Previous by thread: Re: Internal implementation of realloc
- Next by thread: Re: Need Explanation on Lvalue Assignment for the following snippet
- Index(es):
Relevant Pages
|