PDA

View Full Version : wow this is really weird..



sherlockmeister
05-10-2008, 11:15 PM
is there any reason why this should not print 3333?
int i=0,j[]={1,2};
std::cout<<(j[i]|j[++i]);
std::cout<<(j[i--]|j[i]);
std::cout<<(j[i++]|j[i]);
std::cout<<(j[i]|j[--i]);
std::cout<<std::endl;
im using vc++ 2008 express and for me it prints 2211.

R0b0t1
05-11-2008, 06:35 AM
You know what the OR ioerator does, right? Build a logic table.



int i=0,j[]={1,2};

std::cout<<j[i]|j[++i];
std::cout<<j[i--]|j[i];
std::cout<<j[i++]|j[i];
std::cout<<j[i]|j[--i];
std::cout<<std::endl;

sherlockmeister
05-11-2008, 02:08 PM
2 or 1 = 3 (in binary thats 10 or 1 = 11) right?

boberman
05-11-2008, 10:37 PM
Well, your first problem is an order of operations problem, (at least it was with GCC) you need to preform the or before the bitshift operator (using parenthesis). However, even after doing that I was getting the incorrect answer (3213).

The second problem I seem to be running into is that the ++ operator isn't being performed correctly. What it looks like is that the ++ operator is applied after the | operator, Parenthesis don't seem to help here. This may be compiler specific, so it may work for you.

Here is what I used:

std::cout << (j[i] | j[++i]);
std::cout << ((j[(i--)]) | j[i]);
std::cout << ((j[(i++)]) | j[i]);
std::cout << (j[i] | j[--i]);
std::cout << std::endl;

R0b0t1
05-16-2008, 12:44 AM
Seriosly. If you need to know the difference between i++ and ++i, its too complicated.

boberman
05-16-2008, 03:07 AM
:) depends, A good programmer should know the difference between ++i and i++.

R0b0t1
05-16-2008, 10:31 PM
But a good programmer would also know the value of simplicity.

Yakman
05-16-2008, 11:18 PM
i++ and ++i, like everything, should be used in moderation
when the situation is right, they are good

i++ can aid simplicity

example for you



int* arrayOfStuff;
int* i = arrayOfStuff;

int thing1 = *(i++);
int thing2 = *(i++);
int thing3 = *(i++);
int thing4 = *(i++);

//must simpler then this

int thing5 = *i;
i++;
int thing6 = *i;
i++;
int thing7 = *i;
i++;
int thing8 = *i;
i++;

sherlockmeister
05-17-2008, 02:10 AM
lol i known the difference between postfix and prefix (i think thats what its called in java tuts) but if you look at each of those lines they should print 3.
first line:
j[i] (i=0 so j[0]=1) | j[++i] (++i=1 so j[1]=2)
so 1 | 2 = 3 but im getting 2