C problem about Compiler and Memory Theory

135 Views Asked by At

Without calling any "call" or "jump" function, we need to get a output in order of "this is the first" then "this is the second.". In my opinion we need to use "bold" with the use of Memory and instructions. Also we cannot call the function of "study".

#include <stdio.h>

void study()
{
    printf("this is the second.\n");
}

void study2()
{
    int bold[4];
    // can only modify this section BEGIN
    // cant call study(), maybe use study(pointer to function)


    // can only modify this section END
    printf("this is the first\n");
}

int main(int argc, char *argv[])
{
    study2();
    return 0;
}
1

There are 1 best solutions below

7
chux - Reinstate Monica On

Perhaps not what OP had in mind, yet macros do the trick.

#include <stdio.h>

void study() {
  printf("this is the second.\n");
}

void study2() {
  int bold[4];
  // can only modify this section BEGIN
  // Without calling any "call" or "jump" function, 
  #define F1 study
  #define F2 study2
  #define study2() F2(); F1();
  // can only modify this section END
  printf("this is the first\n");
}

int main(int argc, char *argv[]) {
  study2();
  return 0;
}

Output

this is the first
this is the second.

Maybe violates <Also we cannot call the function of "study".>. Depends on "we", if "we" is the portion of code between BEGIN ... END, it is OK.

Else if "we" is anywhere in code, than maybe a direct approach:

void study2() {
  int bold[4];
  // can only modify this section BEGIN
  #define printf(x) printf("this is the first\nthis is the second.\n")
  // can only modify this section END
  printf("this is the first\n");
}

@Peter Cordes suggests a 3rd way, where our modification does not call study().

void study2() {
  int bold[4];
  // can only modify this section BEGIN
  atexit(study);
  // can only modify this section END
  printf("this is the first\n");
}