Support Forums

Full Version: Hacker's test C functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This really isn't a hackers test, its just some really neat code that I was playing with. The whole point of this code is to show the versatility of the void pointer and how you can really be inventive with it....It also demonstrates how easily you can write overly complicated code in C.

Basically the the code just uses a void pointer to hold function addresses and with a few tricks allows us to create a very tricky while statement....

See if you can figure out what's going on...

Copy the code, compile and run. The exe will keep asking for a value until you enter 1234 which is the correct value and then exit.

Code:
#include <stdio.h>
#include <stdlib.h>

unsigned int ans = 1234;

void* foundit(void)
{
    fprintf(stdout, "you guessed the answer->%d\n", ans);
    return (void*)0;
}

void* guessit(void)
{
    unsigned int val;
    fputs("enter a value->", stdout);
    fscanf(stdin, "%d", &val);
    if (val != ans)
    {
        return (void*)&guessit;
    }
    else
    {
        return (void*)&foundit;
    }
}

int main(int argc, char**argv)
{
    void *myans = guessit();
    while (myans = ((void* (*)(void))myans)())
    {}
    return 0;
}

Note: not sure how a C++ compiler will handle this code...you may have to change some parts to get the old lady language(C++) to accept it...
You're returning the memory address of a function, storing it in myans and then calling it in the while loop by casting it to the signature of a function pointer returning void* and taking no parameters ((void* (*)(void)). [Edit: Didn't see that you had said that in your above post, I just saw the code and "see if you can figure out what's going on" Smile]

I thought you needed an ampersand in-front of functions to "legally" get their memory address in C? (ie. return (void*)&guessit;)

Also that code compiles fine in a C++ compiler (well, MSVC anyway).
(11-03-2009, 07:56 PM)MrD. Wrote: [ -> ]I thought you needed an ampersand in-front of functions to "legally" get their memory address in C? (ie. return (void*)&guessit;)

Not for function labels since they are pointers...
(11-03-2009, 08:57 PM)MrD. Wrote: [ -> ]Hmm, apparently most compilers let you omit it, but technically it should be there.

I always used the short format..I guess I should adopt the more correct notation..Tx