pointers (problem in output)

hi all dear members.....
can any one help me to know how this output came for this prog

output.....> 43226

{
int a[]={5,4,2,3,1};
int *p=a;

cout<<++*p<<*p++<<(*p)++<<*++p<<++*p++<<endl;
}
You must not modify a var multiple times in one statement like that. The results are undefined. For example, on my machine, I get 43246, not 43226. And you'll notice that even my output isn't "correct"

do this instead:

1
2
3
4
5
6
7
8
9
10
// cout<<++*p<<*p++<<(*p)++<<*++p<<++*p++<<endl;  BAD BAD BAD
//   never do this!

// good:
cout << ++*p;
cout << *p++;
cout << (*p)++;
cout << *++p;
cout << ++*p++;  // gross and ugly and should be avoided, but not BAD
cout << endl;
i tried like it....and i understand it.......but the above prog is given to us by our teacher and he consider the output 43226(mark true to those boys who give this output)......i am so confused how is it possible...plz any help.................and tnx alot for helping me
Either it's a trick question, or your teacher is wrong.

cout<<++*p<<*p++<<(*p)++<<*++p<<++*p++<<endl;

This does not have reliable output in any situation. According to the C++ standard, it's undefined behavior. There's no way to reliably predict what the output will be. There is no "correct" output because the output is undefined. There's no way to answer this question.

The best answer you can give your teacher is "there is no answer because the code modifies a variable multiple times between sequence points, which results in undefined behavior according to the C++ language standard".

EDIT:

In case that doesn't satisfy your teacher, you can elaborate further and say:

"However, the below code:

1
2
3
4
5
6
7
8
9
int a[]={5,4,2,3,1};
int *p=a;

cout << ++*p;
cout << *p++;
cout << (*p)++;
cout << *++p;
cout << ++*p++;
cout << endl;


outputs XXXXX, because <put your explanation here>"
Last edited on
tnx dear............good reply
Topic archived. No new replies allowed.