C++ fun

Posted on:April 11 2005

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. :)





Comments:


If you are still guessing, take a look here :) http://www.research.att.com/~bs/bs_faq2.html#evaluation-order
niko
Quote
2005-04-11 22:33:00


BecaI usuall
herve
Quote
2005-04-12 00:24:00


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
Quote
2005-04-12 00:27:00


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
Quote
2005-04-12 06:37:00


Right. And because most compilers don't throw warnings about it, most people don't know.
niko
Quote
2005-04-12 09:01:00


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
Quote
2005-04-15 05:51:00


Add comment:


Posted by:


Enter the missing letter in: "Int?rnational"


Text:

 

  

Possible Codes


Feature Code
Link [url] www.example.com [/url]
Bold [b]bold text[/b]
Quote [quote]quoted text[/quote]
Code [code]source code[/code]

Emoticons