Electronics > Beginners

C Program to find maximum between three number using nested if

<< < (4/4)

ve7xen:
Of all the obfuscated examples proposed


--- Code: ---int max = num1;
if (num2 > max) max = num2;
if (num3 > max) max = num3;

--- End code ---

And


--- Code: ---// Or the normal comparison based binary max(int, int)
max = std::max(num1, std::max(num2, num3));

--- End code ---

generate identical and the shortest assembly in pretty much every optimizing compiler. clang's trunk is the cleverest and turns all the proposed examples into effectively identical assembly. There appears to be zero value, and in some cases negative value, in the obfuscation / optimization / fun  :-DD.

https://gcc.godbolt.org/z/qtSChD

Brumby:
I'm all for elegance, optimisation and efficiency ... but let's help the OP stand on their own before we throw them into the decathalon.


To the OP... If a lot of this confuses you at the moment - don't worry.  Geeks often get caught up in their own world - software or hardware!

gbaddeley:

--- Quote from: jesuscf on January 30, 2020, 06:30:47 pm ---max=num1;
if(num2>max) max=num2;
if(num3>max) max=num3;

--- End quote ---

General solution for a zero based array a of n integers:

int i,m;
.....
m=MIN_INT;
for( i=0 ; i<n ; i++ ) if( a[ i ]>m ) m=a[ i ];

admiralk:
This sounds like a school assignment and if nested if statements are a requirement almost every suggestion has been incorrect. One of the things school problems are supposed to teach is how to solve the problem. in other words understand the requirements. In this case, I think khatus is over thinking the problem. The answer is clearly stated twice in the question.

Navigation

[0] Message Index

[*] Previous page

There was an error while thanking
Thanking...
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod