Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which part of this C code is missing or needs to be altered?

For my assignment, I have to fill in missing parts of the C code below. However, I am not sure which parts are missing or which part I have to fill in. I have a sample assembly code which this code will generate, but do not know which parts I have to change to get my expected result. I am just looking for clarification.

typedef enum {MODE_A, MODE_B, MODE_C, MODE_D, MODE_E} mode_t;
long switch3 (long *p1, long *p2, mode_t action) {
  long result = 0;
  switch(action){
  case MODE_A:
  case MODE_B:
  case MODE_C:
  case MODE_D:
  case MODE_E:
  default;
  }
  return result;
}

Other points:

  • There may be cases that should be written in the C code with a fall-through
  • Code shows branching on an enumerated type value in a switch statement. (Question: what exactly does this mean in simple terms? My professor provided a complex definition that I do not understand.)

Assembly code result example:

# p1 in %rdi, p2 in %rsi, action in %edx
.L2:                         # MODE_E
      movl    $27, %eax
      ret
.L7:                         # MODE_A
      movl    (%rsi), %rax
      movq    (%rdi), %rdx
      movq     %rdx, (%rsi)
      ret
.L5:                         # MODE_B
      movq     (%rdi), %rax
      addq     (%rsi), %rax
      movq      %rax, (%rdi)
      ret
.L4:                         # MODE_C
      movq     $59, (%rdi)
      movq     (%rsi), %rax
      ret
.L3:                         # MODE_D
      movq     (%rsi), %rax
      movq      %rax, (%rdi)
      movl      $27, %eax
      ret
.L8:                         # default
      movl      $12, %eax
      ret
like image 560
Jaden Avatar asked Mar 31 '16 07:03

Jaden


1 Answers

As it's an assignment, I won't give you the code. But here is a clarification about those 2 points.

A switch() case can generally be seen as a block like:

if(myvar == ...){
    //branch1
} else if(myvar == ...){
    //branch2
}
...

Each if is a branch and in your case, each branch condition depends on an Enum value. That should answer the branching on an enumerated type value in a switch statement question.

I wrote "generally" because, in fact a switch case is more like a asm jump if equals. so once it reach the correct case all the following code will be executed, even the code in the next casestatements. You have to handle this by stopping programmatically the switch block (You either break it or return). That's for the fall-through point.

You can find plenty of site explaining how a switch case works.

Now you have to fill each casewith the correct implementation -- it seems to be permutations.

like image 192
jhamon Avatar answered Nov 15 '22 20:11

jhamon