Question:
Maximum of (A, B) in C programming?
A
2008-09-21 14:45:28 UTC
Is there a header file that has a max(a,b) and min(a,b) method in it?
If so, what is the name of this header file, and as an example, please write a line of code about how to find the max of numOne and numTwo.

If one doesn't exist, I know the logic in how to write it, just not the syntax. If running my program goes through the main() method, returning 0 at the end, where and how would I put my max(double a, double b) method, and how would I call it?

I know my stuff, but I was taught in C++/Jave, this is C...
Five answers:
Michael F
2008-09-21 15:06:54 UTC
A > B ? A : B;//this is a simple logical-operator use of max, it's good for simple, two-variable max.
2016-12-17 17:58:21 UTC
C Programming Max Function
Yvette
2015-08-06 18:37:47 UTC
This Site Might Help You.



RE:

Maximum of (A, B) in C programming?

Is there a header file that has a max(a,b) and min(a,b) method in it?

If so, what is the name of this header file, and as an example, please write a line of code about how to find the max of numOne and numTwo.



If one doesn't exist, I know the logic in how to write it, just not the syntax. If...
Tizio 008
2008-09-21 15:10:01 UTC
C has not method but function.

I dn't know if there's something like max min already ready inside an include. anyway you can use a define rather than real code, or write an inline function...

e.g.

#define max(A,B) (((A)>(B))?(A):(B))

this line is for the pre-processor; do not put a ; ad the end, do not strip (), they assure you the right precedence... it works like a macro. this macro works whatever A and B are, provided that the > operator has meaning.



since the C does not supporto overloading, the "function" version is more limited to the var type you write it for.



functon must be outisde the main function



inline double max(double A, double B)

{

return (A>B)?A:B;

}



int main(...)

{ ...

}



you could put it after main too... but then the compiler could complain since the usage appear before the definition... so it is a good idea to put function before they are used, or use a "declaration" (maybe prototype is the right name), like

double max(double, double);

...

main() { }



double max(double a, double b)

{

...

}
suitti
2008-09-21 15:47:52 UTC
I thought it was in a header somewhere. Under Linux, max() is defined in /usr/include/g2c.h - but that's fortran. And, it doesn't define min(). That's in

/usr/include/X11/Xlibint.h



How bizzare. This is what i'd use:



#ifndef max

#define max(a,b) ((a) > (b) ? (a) : (b))

#endif

#ifndef min

#define min(a,b) ((a) < (b) ? (a) : (b))

#endif


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...