An easy one:
Code:int a[] = {11,12,13,14,15};
int* ap = a - 1;
Printable View
An easy one:
Code:int a[] = {11,12,13,14,15};
int* ap = a - 1;
That's just evil.
And yet that's correct :)
Are you absolutely sure? The standard is far more precise about what operations are allowed on pointers and when than what any implementation actually enforces.
Hmm, according to the C faq link it's not correct.
I meant Dave was correct on how he interpreted the code. It's a way to implement a unit-based array.
EDIT: I was actually unware at the fact that despite there existing no dereferencing it could still produce undefined behavior. But Dave hit it on the nail at the code usage.
But is there actually systems that behaves differenty than expected, trying to "wrap around" for example?Quote:
Originally Posted by Mario F.
> But is there actually systems that behaves differenty than expected, trying to "wrap around" for example?
Some people don't like to admit they were wrong, apparently.
While the link provided by Dave explains why it is undefined behavior, the following link from the Numerical Recipes book website shows an extract of the new Numerical Recipes for C++ book. Take a look at page 10. It's worth your time... although probably make you mad.
http://www.numerical-recipes.com/cpppages/chap1sel.pdf
For fun:Code:void foo(unsigned int value)
{
unsigned int bit;
for ( bit = /* msb */(~0U >> 1) + 1; bit > 0; bit >>= 1 )
{
putchar("01"[!!(value & bit)]);
}
putchar('\n');
}
Ain't that just a base 2 itoa, printing directly?
Mario F: I think you missunderstod me, I was just being curious.
Oh. I have. Sorry. I read that as a rethorical question.Quote:
Originally Posted by TriKri
Yeah. I was kind of shooting for something along the line of, "the !!(value & bit) results in a one or a zero if the selected bit is set in value or not, so you can safely index into the string literal", or something.Quote:
Originally Posted by CornedBee
Code:putchar("01"[!!(value & bit)]);
what if you'd do (value & bit) != 0 ? isnt that either 0 or 1 ?Quote:
Originally Posted by Dave_Sinkula
But!! isn't!! double!! exclaimation!! so!! leet!! ??!!
Ah! Not the leet thing again!