Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me understand this Strange C++ code

Tags:

c++

This was a question in our old C++ exam. This code is driving me crazy, could anyone explain what it does and - especially - why?

int arr[3]={10,20,30};
int *arrp = new int;

(*(arr+1)+=3)+=5;
(arrp=&arr[0])++;

std::cout<<*arrp;
like image 978
java lava Avatar asked Jun 06 '10 17:06

java lava


People also ask

What is code C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C coding?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


2 Answers

This statement writes to the object *(arr+1) twice without an intervening sequence point so has undefined behavior.

(*(arr+1)+=3)+=5;

This statement writes to the object arrp twice without an intervening sequence point so has undefined behavior.

(arrp=&arr[0])++;

The code could result in anything happening.

Reference: ISO/IEC 14882:2003 5 [expr]/4: "Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression."

like image 173
CB Bailey Avatar answered Oct 14 '22 18:10

CB Bailey


(*(arr+1)+=3)+=5;

arr + 1 - element with index 1
*(arr + 1) - value of this element
(arr + 1) += 3 - increase by 3
(
(arr+1)+=3)+=5 - increase by 5;

so arr[1] == 28

(arrp=&arr[0])++;

arr[0] - value of element 0
&arr[0] - address of element 0
arrp=&arr[0] - setting arrp to point to elem 0
(arrp=&arr[0])++ - set arr to point to elem 1

result: 28

like image 33
Andrey Avatar answered Oct 14 '22 16:10

Andrey