Absolute Value

Started by
12 comments, last by kelaklub 20 years, 9 months ago
quote:Original post by Anonymous Poster
how about the old fascion way?

if i < 0
i *= -1

i is the variable in question, but maybe thats just to slow.


I''d never do it that way, even if I don''t need speed. Why use a multiplication? Whats wrong with i = -i? i = -i will most likely translate into NEG AX (or some other register).
Advertisement
quote:Original post by drslush
quote:Original post by Anonymous Poster
how about the old fascion way?

if i < 0
i *= -1

i is the variable in question, but maybe thats just to slow.


I''d never do it that way, even if I don''t need speed. Why use a multiplication? Whats wrong with i = -i? i = -i will most likely translate into NEG AX (or some other register).


Is this guaranteed that the following code will translate into NEG AX?
quote:Original post by Miserable
The people who wrote your compiler presumably used the best and most efficient way available.


This generalization is not right in all situations. Most notably the stock compiler implementation of rand() is notoriously poor, even in otherwise good compilers'' C libraries. I don''t know about fabs() in particular (though I would assume your generalization does indeed hold), but applying this statement to the whole of the C library can lead to trouble.

quote:Original post by Miserable
Finally, remember that premature optimisation is the root of all evil.


I couldn''t agree with this more. Before even thinking about optimizing at such a small level, run a profiler on your code to see where the optimizations are needed.


GG
quote:Original post by kelaklub
Would anyone know how to fix this. I am using the bloodshed dev-c++ compiler, and they claim that you have to enter inline assembly instructions in the AT&T not the Intel syntax, which I have done, but only if I make i global will this compile. Then too the result is inncorrect. Thank You.

int main(){        int i = -5;         __asm("mov %eax,_i");               __asm("cdq");               __asm("xor %eax,%edx");               __asm("sub %eax,%edx");        __asm("mov _i,%eax");       cout<<"\n"<<i<<"\n";        system("PAUSE");	    return 0;}


in at&t syntax it''s

__asm("movl _i,%eax");
__asm("cdq");
__asm("xorl %edx,%eax");
__asm("subl %edx,%eax");
__asm("movl %eax,_i");

at&t uses the first operant as source and second as dest. intel uses the first operant as dest and the second as source.

My Site

This topic is closed to new replies.

Advertisement