This classic ioccc entry is a Hello World program written in C. Can anyone please provide an explanation of how it works?
Original code (syntax highlighting intentionall
Not in a mind of taking this apart completely, but there are some hints:
'-' - '-'
is obfuscated for 0
'/' / '/'
and the i / i
in read() are obfuscated for 1
Remember that [] is commutative, i.e. i["] is the same as
"] (having a char array and pointing at the i'th element of it). The content of the string doesn't matter in any way, only its length is used to define the number of iterations of the loop. Any other string of the same length (incidentially, the same length as the output...) would work. After that number of iterations, "string"[i] returns the null character that terminates the string. Zero == false, loop terminates.
With that, it should be comparatively easy to figure out the rest.
Edit: The upvotes made me interested enough to look at this some more.
Of course, i++ + "Hello, world!\n"
is the same as "Hello, world!\n"[ i++ ]
.
codelark already pointed out that 0
is the fid for stdout. (Give him +1 for that, not me. Just mentioning it for completeness.)
The i
in read()
is of course local, i.e. the i--
in read()
does not affect the i
in main()
. Since the following i / i
is always 1
anyway, the --
operator does nothing at all.
Oh, and tell the interviewer to fire whoever wrote this code. It does not do error checking on the return value of write()
. I can live with notoriously badly-written code (and have, for many years), but not checking for errors is worse than bad, that's faulty. :-)
The rest is just some third-grade maths. I'd pass that to an intern. ;-)