solution C Puzzle 10 To 13


solution C Puzzle #10
Solution_1:
void main()
{
if (printf("Hello world!\n"))
 {}
}

Solution_2:

#include<stdio.h>
void main()
{
puts ("Hello, world!");;
}

Because i have told you not to use 'a' semicolon.
So this could also be the answer.

solution C Puzzle #11
Solution:
error in the line int
a
=
1,2;
Here the declaration and definition is happening at the same time and hence compiler
associates/initializes a to 1 but for 2 it considers as variable and since it
is a not a valid variable(variable names cannot start with digits) it throws
out an error.

solution C Puzzle #12
Answer: By my friend Fazlur The printf returns the number of chars that it prints on the stdout, in this
case

First the inner printf prints 45, i.e. 2 chars, the inner printf returns 2
to the surronded printf and it returns 1 to the outermost printf  and so
on... the output would be,

4521

coz, first the innermost printf prints and then the middle printf and then
the outermost ....

solution C Puzzle #13


It's called Duff's device and you can read about it on wikipedia.
It takes care of one problem with an unrolled loop: there could be a non-integer number of passes needed. One method is to deal with this outside the main loop, but it's more efficient to use Duff's device which uses a very fast jump table and avoids extra looping overhead dealing with the odd number of operations.
In your example, which is a memory copy, please compare to the naive version:
void memcpy(char* dst, char* src, size_t count)
{
   begin:
     if (count-- == 0) return;
     *(dst++) = *(src++);
     goto begin;
}
To copy 15 bytes, this does the following:
test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count, copy, loop, test count
Note how many times the "test count" and "loop" operations must be done.
Using duff's version which you showed, it is much simpler:
jump based on count, copy, copy, copy, copy, copy, copy, copy, test count, loop, copy, copy, copy, copy, copy, copy, copy, copy, test count
which saves over half the steps.


Answer by my friend:
It's valid. It's a very old-school loop unroll.
Basically, instead of checking the count for every character that's being copied to determine when to stop, it only has to check ceil(n/8) times.
The register keyword is just a compiler hint to suggest that the compiler try to keep that value in a register instead of shuffling it in and out of main memory.
Obviously stuff like this isn't really necessary anymore (memcpy() is likely to have a very fast implementation on whatever machine you're coding for) but tricks like this used to actually provide pretty decent performance wins.

No comments:

Post a Comment