First see the syntax of read
and write
function in C and what they do:
ssize_t read(int fildes, void *buf, size_t nbyte);
The read()
function shall attempt to read nbyte
bytes from the file associated with the open file descriptor, fildes
, into the buffer pointed to by buf
.
ssize_t write(int fildes, const void *buf, size_t nbyte);
The write()
function shall attempt to write nbyte
bytes from the buffer pointed to by buf
to the file associated with the open file descriptor, fildes
.
Now, rewriting your for
loop as
for(;i["]<i;++i){--i;}"]; read('-' - '-', i++ + "hell\o, world!\n", '/' / '/'));
Starting with i["]<i;++i){--i;}"]
;
"]<i;++i){--i;}"
is a string. In C, if
char ch;
char *a = "string";`
then you can write ch = "string"[i]
which is equivalent to i["string"]
(as a[i] = i[a]
). This basically add the address of the string
to i
(i
is initialized to 0
as it is globally defined). So, the i
is initialized with the starting address of string hell\o, world!\n
.
Now the point is that the for
loop is not iterating only once!
The expression read('-' - '-', i++ + "hell\o, world!\n", '/' / '/')
can be rewritten as (for the sake of convenience);
read(0, i++ + "hell\o, world!\n", 1)
^ read only one byte (one character)
Now what it will do actually is to call read
and increment i
(using its previous value). Starting address of string hell\o, world!
get added to i
. So the first call of read will just print H
. On next iteration the i
is incremented (contains the address of next character) and call to read will print the next character.
This will continue until i["]<i;++i){--i;}"]
becomes false
(at \0
).
Overall the behavior of code is undefined!
EXPLANATION for UB:
Note that a function call f(a,b,c)
is not a use of the comma operator and the order of evaluation for a
, b
, and c
is unspecified.
Also C99 states that:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.
Hence the call
write(j/p+p, i-- -j, i/i);
invokes UB. You can't modify and use a variable in the same expression. The compiler should raise a warning
[Warning] operation on 'i' may be undefined [-Wsequence-point]