+ 5

Can someone explain this behavior?

The following JS code acts weirdly: const arr = Uint8Array.of(255); const x = ++arr[0]; arr[0] // returns 0 x // returns 256 But the C/C++ equivalent is normal: uint8_t arr[] = {255}; int x = ++arr[0]; arr[0] // returns 0 x // returns 0 https://code.sololearn.com/crz9XRm42BVZ/?ref=app https://code.sololearn.com/WAfjzgIHbF4y/?ref=app

18th Feb 2019, 2:37 PM
Aaron Sarkissian
Aaron Sarkissian - avatar
4 Respostas
+ 15
uɐᴉssᴉʞɹɐs uoɹɐɐ may be this link will give some information. As I don't know javascript till now but in C as 8 bit number highest value is 255 bits which is calculated by 2^k where k is the bits so by incrementing the value of array the overflow situation occurs by which array again restart from 0 and value 0 is returned as output In javascript this link may help in which it says that it is due to type manipulation cost range is increased as it typecast to number which range is higher maybe this link will give information about this or any javascript expert https://dev.to/antogarand/javascript-typed-arrays-unexpected-overflow-1e1p https://nullprogram.com/blog/2019/01/23/
18th Feb 2019, 3:05 PM
GAWEN STEASY
GAWEN STEASY - avatar
+ 5
It appears that JS performs the pre-increment by first loading the value into a register, then incrementing, then saving the result into each of the two destinations. C takes a potentially faster, direct addressing approach. First increment the original memory location, then copy the result into x's location -- by using memory-to-memory transfer if the CPU supports it. Fewer instructions are required.
18th Feb 2019, 11:11 PM
Brian
Brian - avatar
+ 4
#include <stdio.h> #include <stdint.h> int main() { int arr[] = {255}; int x = ++arr[0]; printf("%i\n", arr[0]); // returns 0 printf("%i\n", x); // returns 0 return 0; }
3rd Mar 2019, 7:07 PM
Sanjana Chouhan
Sanjana Chouhan - avatar
+ 3
Thanks Brian and GAWEN STEASY! I'll checkout the links ✌️
19th Feb 2019, 5:25 AM
Aaron Sarkissian
Aaron Sarkissian - avatar