C++ fun

What's the result of this code?

a[c++] = b[c++];

And what's the result of this one?

a[++c] = b[++c];

Fun for the brain. And pretty senseless. If you write code like this, throw it away, and write it again, more clearly. So that you or your co-worker will understand it easily later too. :)

six comments, already:

If you are still guessing, take a look here :) http://www.research.att.com/~bs/bs_faq2...
niko - 11 04 05 - 22:33

BecaI usuall
herve () - 12 04 05 - 00:24

Sorry for last comment (typing problem)... What I was trying to write is that I usually never use the ”++”, except for just incrementation in a loop for example. I always have difficulties to understand how it will work if it’s not over-simple…
herve () - 12 04 05 - 00:27

That’s code with an undefined result (per specification), because it’s an expression in which the variable c gets modified more than once.
ak - 12 04 05 - 06:37

Right. And because most compilers don’t throw warnings about it, most people don’t know.
niko - 12 04 05 - 09:01

More c fun:

int c = 1;
c = ++c + ++c;

Whats the value of c? Try again with a different compiler and optimization flags. Now what’s the value of c? :) The C FAQ explains why this is bad, bad code!
—-

char c[ ] = “foo”;
0[ c ] = ‘b’;
c[ 1 ] = ‘a’;
2[ c ] = ‘r’;

c[ 1 ] = = 1[ c ] because *( c + 1 ) = = *( 1 + c)
zenakuten () - 15 04 05 - 05:51


Name:  
Remember personal info?
yes
no
Email (optional):
URL (optional):
Enter "layered" (antispam):
Comment:Emoticons / Textile

  ( Register your username / Log in )

Notify: Yes, send me email when someone replies.  

Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.
Note: If you type in your email adress above, it will be visible to other visitors, although it will be hidden for bots using javaScript.