0

I'm trying to check even odd in assembly, using a 32-bit NASM, the code is working fine for odd numbers, but for even numbers it is giving output

Even
Odd
Odd

My code is,

section .data
    even db "Even", 0xa;
    odd db "Odd", 0xa;
    lene equ $-even;
    leno equ $-odd;

section .text
    global _start;

_start:
    mov ax, 0x4;
    and ax, 1;
    jz evenn;
    jnz oddd;
    jmp outprog;

evenn:
    mov eax, 4;
    mov ebx, 1;
    mov ecx, even;
    mov edx, lene;
    int 0x80;

oddd:
    mov eax, 4;
    mov ebx, 1;
    mov ecx, odd;
    mov edx, leno;
    int 0x80;

outprog:
    mov eax, 1;
    int 0x80;
  • 5
    lene is 9, so evenn prints “Even/Odd”. Then after evenn, there’s no jump to outprog, so it prints”Odd” again. – prl Aug 29 '20 at 18:32
  • @pri I think that should be an answer instead of a comment. – luser droog Aug 29 '20 at 18:33
  • 3
    The three branches in a row in start are an indication that you should read about how control flow works. All three should be replaced with one: `jnz oddd`. – prl Aug 29 '20 at 18:34
  • @luserdroog: Yes, but fortunately it already is an answer on [In NASM labels next to each other in memory are causing printing issues](https://stackoverflow.com/q/26897633) so nobody needs to repeat it here. – Peter Cordes Aug 29 '20 at 18:54
  • thanks @prl for the clarification on control flows, I was thinking of them as separate from the main program – neuromancer Aug 29 '20 at 19:00
  • thanks @luserdroog for the reference question, apparently there was an extra line being printed because of declaration mistake – neuromancer Aug 29 '20 at 19:01

1 Answers1

0
void fun ( int x )
{
   int y;
   y=x&1;
   if(y==0)
   {
     show_even();
   }
   else
   {
     show_odd();
   }
}

is essentially what you are trying to do and you start off in the right direction, but after the show_odd or show_even you need to take separate paths to the end of the function you don't want to go through the second path

Your even path is going through this code:

evenn:
    mov eax, 4;
    mov ebx, 1;
    mov ecx, even;
    mov edx, lene;
    int 0x80;

oddd:
    mov eax, 4;
    mov ebx, 1;
    mov ecx, odd;
    mov edx, leno;
    int 0x80;

which prints Even then falls into the code that prints Odd. You want to branch to outprog after printing Even.

The C code above as a model instead of this:

void fun ( int x )
{
   int y;
   y=x&1;
   if(y==0)
   {
     show_even();
   }
   show_odd();
}

where odd is always printed no matter what.

And you can optimize this into a single instruction.

jz evenn;
jnz oddd;
jmp outprog;

vs

jnz oddd;

Think through the code execution path.

halfer
  • 19,824
  • 17
  • 99
  • 186
old_timer
  • 69,149
  • 8
  • 89
  • 168