Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ strange std::cout behaviour using pointers [duplicate]

Tags:

c++

iostream

cout

Possible Duplicate:
What is the correct answer for cout << c++ << c;?

I just ouputted text, when I suddenly noticed.

#include <iostream>
int main()
{    
 int array[] = {1,2,3,4};                 
 int *p = array;

    std::cout << *p << "___" << *(p++) << "\n";
    // output is  1__1. Strange, but I used  brackets! it should be at
    // first incremented, not clear.
    p = array;


   std::cout << *p << "___" << *(++p) << "\n";
   // output is 2_2   fine, why first number was affected? I didn't intend 
   // to increment it, but it was incremented
   p=array;


   std::cout << *p << "___" << *(p + 1) << "\n";
   // output is 1_2 - as it was expected
   p = array;

 return 0;
}

Such behaviour is strange for me, why is it so?

like image 734
Tebe Avatar asked Dec 06 '22 11:12

Tebe


1 Answers

You are causing undefined behaviour, so anything can happen and there's no point in speculating about why.

The expression

std::cout<<*p<<"___"<<*(p++)<<"\n"

Is one example: the order of evaluation of all the things between << is unspecified, so *p and *(p++) are unsequenced with respect to each other (i.e. the compiler is not required do do either one first). You are not allowed to modify a variable and then use it without the modification and usage being sequenced, and so this causes undefined behaviour.

The same thing applies to all the other places in that program where a variable is modified and used unsequenced separately in the same expression.

like image 76
Seth Carnegie Avatar answered Dec 09 '22 14:12

Seth Carnegie