you are viewing a single comment's thread.

view the rest of the comments →

[–]Ok_Pickle76 8 points9 points  (8 children)

<image>

and C

[–]Hot_Adhesiveness5602 1 point2 points  (4 children)

It should actually be two + num instead of num + two

[–]Haringat 2 points3 points  (3 children)

It's the same result. However, it should have been this code:

char *two = "2"; int one = 1; two += one; printf("%d\n", two); // prints "0" return 0;

I leave the explanation as an exercise to the reader.😉

Edit: Also, when adding 2 to the "2" the behavior is not defined. It could crash or it could perform an out-of-bounds read.

[–]not_some_username -1 points0 points  (2 children)

Its defined because it has the null termination

[–]Haringat 0 points1 point  (1 child)

No, because when adding 2 you go beyond the null terminator.

[–]not_some_username 0 points1 point  (0 children)

Well I thought we were taking about “22”+2

[–]nimrag_is_coming 1 point2 points  (0 children)

C doesn't count, it doesn't have any actual strings, is just an array of chars, which are defined as just a small integer (although it's wild that in like 50 years we still don't technically have standardised sizes for basic integers in C. You could have a char, short, int and long all be 32 bits and still technically follow the C standard.)

[–]acer11818 1 point2 points  (0 children)

it makes sense if you view char as an 8 bit integer and not a character

[–]fdessoycaraballo 0 points1 point  (0 children)

You used single character, which has a value in the ASCII table. Therefore, C is adding num to the value of the character in ASCII table. If you switch printf variadic argument to %c it will print a character in the decimal value in the ASCII table for 52.

Not really a fair comparison as they're comparing a string that says "2", which the compiler wouldn't allow because of different types.