Click here to Skip to main content
15,888,062 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have some problem when I'm using 'asm' in C++.
I need to find max value in array, I wrote the code but it doesn't compare.

What I have tried:

void func1(int x[],int lenght){ // Find MAX 
    
    int max, z = x[0]; //Make first elem is MAX
    
    __asm__ volatile 
        (   
            "movl %1, %%eax;"
            "movl %%eax, %0;"
            : "=r" ( max )        
            : "r" ( z )         
            : "%eax" 
        );

    
    for(int i = 1 ; i < lenght; i++) //From second element to end
    {
        __asm__ volatile
        (   
            "movl %1, %%ebx;" // Move x[i] to EBX
            "cmpl %%ebx,%%eax;" 
            "jl DONE;"// If EAX less EBX JUMP to 'DONE'
            "DONE: movl %%ebx,%%eax;" // MOVE EBX to EAX
            "movl %%eax , %0" // MOVE EAX to 'max'
            :"=r"(max)
            :"r"(x[i])
        );
    }

    cout << "MAX" << endl;
    cout << max << endl;
}
Posted
Updated 3-Apr-20 5:39am
Comments
Rick York 22-Mar-20 23:15pm    
This is how length is spelled.

I don't know assembler language because I have never found it necessary. I once wrote an on-the-fly machine code generator though. I did it by figuring out what machine code was emitted by writing code snippets in C and then examining the compiler's assembler and machine code listings. I recommend doing that for this code. It is quite simple so write it in C and then look at what the compiler does with the code in its assembler listings. That's how I would proceed anyway.
Nabiev Anush 24-Mar-20 6:05am    
Thank you for advice !
Stefan_Lang 26-Mar-20 3:48am    
That's actually very good advice: maybe it will give people an idea just how pointless it is nowadays to provide the assembler code by yourself ;-)

Totally compiler dependent. Your case seems like the GCC. In MSVC it will be more like:

__asm {
   mov al, 2
   mov dx, 0xD007
   out dx, al
};
 
Share this answer
 
v2
I use another way how to find max value in array.
I used MS Visual Studio.

C++
include 

define LEN 6

using namespace std;

int task1();

int main() {
    cout << "Task 1: " << task1() << endl;
    return 0;
}

int task1() {
    int mas[LEN] = { 1, 2, 7, 4, 5, 6 };

    __asm {
        xor eax, eax
        mov ecx, LEN

        cycle_mark :
            mov edx, [mas + 4 * ecx]
            cmp eax, edx
                jl max_mark
                jg check_mark

        max_mark :
            mov eax, edx

        check_mark :
            dec ecx
            cmp ecx, 0
                jne cycle_mark
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900