Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print 1 to 100 without using loops, recursion, or goto statements in c programming? [closed]

Tags:

I found this solution from the internet.

#include <stdio.h>
#include <stdlib.h>
int n = 0;
void first() {
    void* x;
    printf("%d\n", ++n);
    if (n >= 100) {
        exit(0);
    }   
    *((char**) (&x + 4)) -= 5;
}
int main() {
    first();
    return 1;
}

Can someone explain me the meaning of the line *((char**) (&x + 4)) -= 5;?

like image 815
sagnikdas Avatar asked Jul 08 '16 08:07

sagnikdas


1 Answers

The exercise makes absolutely no sense. That being said, it would seem your "hack" is trying to emulate the behavior of setjmp/longjmp, which stores/restores the state of the execution environment, such as the program counter.

// Silly code to solve artificial problems. Don't write programs like this.
#include <stdio.h>
#include <setjmp.h>

void silly_print (int max)
{
  jmp_buf jb;
  int n = setjmp(jb);
  printf("%d\n", ++n);
  if(n < max)
  {
    longjmp(jb, n);
  }
}

int main() 
{
  silly_print(100);
}

Note: setjmp/longjmp are considered dangerous because they could cause all manner of unintended side effects. They are also considered bad practice since they can be used for spaghetti programming, as done in the code above

like image 192
Lundin Avatar answered Oct 11 '22 13:10

Lundin