Crazy but valid C...

Discussion in 'C Programming' started by umesh.kalappa0, Jan 21, 2014.

  1. Hi All,

    Below code is that valid C Construct for the functions call .

    int test()
    {
    printf("test\n");
    }

    int main()
    {
    (***(int(****)(void))test)();
    }

    Thanks for the inputs
    ~Umesh
     
    umesh.kalappa0, Jan 21, 2014
    #1
    1. Advertisements

  2. umesh.kalappa0

    Xavier Roche Guest

    (valid, but does not build with -Werror and proper warnings due to
    strict aliasing issues)

    This is due to the "A declaration of a parameter as "function returning
    type" shall be adjusted to "pointer to function returning type"" rule,
    and the obscure 6.3.2.1 4: “A function designator is an expression that
    has function type. Except when it is the operand of the sizeof operator,
    the _Alignof operator, or the unary & operator, a function designator
    with type “function returning type” is converted to an expression that
    has type “pointer to function returning type”

    The wording is anything but clear, but unless I missed something, it
    basically means that & and * yield the same pointer location for functions.
     
    Xavier Roche, Jan 21, 2014
    #2
    1. Advertisements

  3. No not valid. Tidied up and simplified to show the problem:

    #include <stdio.h>

    int test(void) { printf("test\n"); }

    int main(void)
    {
    (*(int(**)(void))test)();
    }

    The type int(*)(void) is a function pointer type. The type
    int(**)(void) is an object pointer type. The conversion is not defined
    to be meaningful, and de-referencing the resulting pointer is almost
    certainly going to go horribly wrong. Doing that multiple times just
    makes the matter worse.

    What does your compiler say about it? If it is silent -- ask for more
    warnings. For gcc, -pedantic disables GNU extensions and makes gcc
    report this problem.
     
    Ben Bacarisse, Jan 21, 2014
    #3
  4. The _Alignof case does not apply, since (for unclear reasons) the
    _Alignof operator can be applied only to a parenthesized type name, not
    to an expression. This is unlike the sizeof operator. The reference to
    _Alignof (for both array and function expressions) is an error in the
    N1570 draft, corrected in the released 2011 ISO C standard.
     
    Keith Thompson, Jan 21, 2014
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.