vaibhav
vaibhav

Reputation: 396

How does this code print a series of numbers in C?

This is a basic C program and it doesn't use looping or conditions to print digits. I wanna know how it does what it does, along with purpose of "exit" and "main". Is main used for recursion here?

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

void main(int j) {
    printf("%d\n", j);
    (&main + (&exit - &main)*(j/1000))(j+1);
}

Upvotes: 1

Views: 367

Answers (4)

user2175492
user2175492

Reputation:

This one actually compiles to assembly that doesn't have any conditionals:

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

void main(int j) {
  printf("%d\n", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}

Try: Added '&' so it will consider the address hence evading the pointer errors.

This version of the above is in standard C since it doesn't rely on arithmetic on function pointers:

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

void f(int j)
{
    static void (*const ft[2])(int) = { f, exit };

    printf("%d\n", j);
    ft[j/1000](j + 1);
}

int main(int argc, char *argv[])
{
    f(1);
}

Upvotes: 2

Sneftel
Sneftel

Reputation: 41474

Suppose that j is 500. Then (&exit - &main) is something (doesn't matter what) and (j/1000) is 0, so (&main + (&exit - &main)*(j/1000))(j+1) is effectively main(501). In contrast, if j is 1000, then (j/1000) is 1, which means (&main + (&exit - &main)*(j/1000)) is the same as (&main + (&exit - &main)) (which is to say, &exit), so it calls exit(1001) instead.

Upvotes: 5

quantdev
quantdev

Reputation: 23793

  • &main is the address of the main function (entry point of any C program)
  • &exit is the address of the exit function (terminates the program)

Consider your statement:

(&main + (&exit - &main)*(j/1000))(j+1);



if j < 1000, then 
 (&exit - &main)*(j/1000) == 0 (integers division)
 // So we are calling main(j+1)
else if j == 1000
 (&exit - &main)*(j/1000) == &exit - &main
 // So we are calling (&main + &exit - &main)(j+1), which is calling exit(j+1)

So your program is calling main() recursively until j == 1000, at which point it calls exit

This program is so wrong in terms of programming/best practices/etc..., that you should just forget about it.

Upvotes: 3

md5
md5

Reputation: 23699

I suggest it is supposed to work as follow:

  • when j < 1000, call &main + (&exit - &main)*(j/1000) with argument j+1. Since j/1000 == 0, it calls main(j+1).
  • when j = 1000, since j/1000 == 1, it calls &main + (&exit - &main) * 1 == exit.

However, there are a lot of errors in this tiny C program. For instance, void main(int) is not a standard main signature.

Upvotes: 4

Related Questions