max of two integers using ternary operator in C - c

Is there a better way to return the max of two integers using the ternary operator in C?
This is what I have for now
int max(int a, int b)
{
int big = 0;
big = (a>b)?a:b;
return big;
}
But I wanted to write it something like this
#include <stdio.h>
int main(void)
{
printf("%d\n",fun(5,4));
return 0;
}
int fun(int a, int b)
{
(a>b)?(return a:return b);
}
But it gives me an error

The conditional operator (yes, it has a name!) is used to build expressions, so you have to use it where an expression is expected – for example, the expression of the return statement:
return b < a ? a : b;

One improvement you can do is make the function inline
inline int max(int a, int b) {
return a > b ? a : b;
}
See Also An Inline Function is As Fast As a Macro.

return is a statement, not an expression. It can't be used in the middle of an expression.
Also, the two return values of the ternary have to be separate expressions; wrapping them in a single set of parentheses makes them just one expression.
So it should be:
int fun(int a, int b) {
return (a > b) ? a : b;
}

Related

nested macro implementation with # and ## operator

I am writing a generic function which will take macro name and execute correct function.
I am writing a function which will take function name from macro and concatenate this and execute the function.I am adding this header file in my workspace where more than one c file use this macro implementation logic to execute my code.But I am getting error while running the code .
#define STR(name) #name
int convert_f14u18(int a,int b);
int convert_f14s18(int a,int b);
#define VAL_F 14
#define DATA_SIGN u
#define VAL_NUM 18
#define EXECUTE_FUN_NAME(a,b,c,d,e) a##b##c##d##e
#define EXECUTE_STATEMENT(a,b,c,d,e,f) b##c##d##e#f=EXECUTE_FUN_NAME(a,b,c,d,e)
typedef int u32;
u32 add_u32(u32 a,u32 b);
int main() {
//Testing of string macro
printf(STR(Hello));
int numa = 10;
int numb = 20;
int numc = 30;
//int z1 = EXECUTE_FUN_NAME(convert_,f,14,u,18)(numa,numb);
int z1 = EXECUTE_FUN_NAME(convert_,f,VAL_F,DATA_SIGN,VAL_NUM)(numa,numb);
//int z2 = EXECUTE_FUN_NAME(convert_,f,14,s,18)(numa,numc);
int z2 = EXECUTE_FUN_NAME(convert_,f,VAL_F,DATA_SIGN,VAL_NUM)(numa,numc);
printf("\nz1 %d\n",z1);
printf("z2 %d\n",z2);
return 0;
}
int convert_f14u18(int a,int b){
return (a+b);
}
int convert_f14s18(int a,int b){
return (a+b);
}
u32 add_u32(u32 a,u32 b){
return (a+b);
}
Error:../main.cpp: In function ‘int main()’:
../main.cpp:37:76: error: ‘convert_fVAL_FDATA_SIGNVAL_NUM’ was not declared in this scope
int z1 = EXECUTE_FUN_NAME(convert_,f,VAL_F,DATA_SIGN,VAL_NUM)(numa,numb);
Expected result: If I un-comment the lines above of actual macro statement in main statements and comment the current macro statements, I am able to run the code. But I want to make my code run with the current logic .
When replacing a macro, C first replaces each parameter with its argument. So the argument c is replaced with VAL_F, for example. Then it applies the ## operator, which produces convert_fVAL_FDATA_SIGNVAL_NUM in this example. Then C checks the result for additional macros to substitute. However, at that point, the arguments, such as VAL_F, have been made into a single token with ## and are no longer individual tokens that will be replaced.
To deal with this, use one macro to replace the arguments, then use another macro to apply the ## operator. Change:
#define EXECUTE_FUN_NAME(a,b,c,d,e) a##b##c##d##e
to:
#define EXECUTE_FUN_NAME_HELPER(a, b, c, d, e) a##b##c##d##e
#define EXECUTE_FUN_NAME(a, b, c, d, e) EXECUTE_FUN_NAME_HELPER(a, b, c, d, e)

Passing an operator as an argument to a function in C

I want to pass greater than (>) and less than (<) operators as arguments to a function,how is it possible..is there any way to pass those operators as arguments..please any one can help me.
You can do terrible things with macros, but in general, no, you can't do this. You typically accept a two argument function and call it, and that function can use > or < as appropriate, see the sort docs for an example.
That said, it's not super efficient (calling a function through a pointer can't be inlined, and for cheap operations like a > or < comparison, the function call overhead outweighs the comparison work). Making it efficient requires:
Multiple copies of the code, one for each possible operator (possibly generated via macros)
Moving to C++ and using templated code with functors/lambdas that can be inlined properly
There is no way to pass a 'raw' operator, but there are ways to achieve the same result.
The simplest would be a char
int func(char op, int a, int b)
{
if (op == '<')
{
return a < b;
}
else if (op == '>')
{
return a > b;
}
return -l; /* error */
}
A more complex solution would be to use a function pointer to a function that does the operation (similar to the comparator used by the sort method).
You can create a enum and pass it.
Or you can pass in a pointer to a comparison function like this:
#include <stdio.h>
int max(int a, int b, int (*comp)(int, int)) {
if (comp(a, b) < 0) {
return b;
} else {
return a;
}
}
int mycomp(int a, int b) {
return a < b ? -1 : 1;
}
int main() {
printf("%d %d\n", max(1, 2, mycomp), max(2, 1, mycomp));
}
You can write this function by using #define and #. Character #, changes an operator to a string. (for example in #define, #+ = "+").
Sample code:
#include <stdio.h>
#define great(c) ((#c==">")? (1):(0))
int main()
{
printf ("%d", great(>));
return 0;
}
In this code, I passed > as a function argument.

Prepend function call with some code using Macro in C

I have a call to a function foo(a,b,c) in a C file which I want to prepend with some code. Can I do this with macro? Basically, I want to do the following:
Replace
add(a,b,c)
by
foo()
add(a,b,c)
Is it possible to achieve this with macro?
#include <stdio.h>
int add(int a, int b, int c) {
return a + b + c;
}
void foo() {
printf("Foo!\n");
}
int add2(int a, int b, int c) {
foo();
return add(a, b, c);
}
#define add(a, b, c) add2((a), (b), (c))
int main() {
printf("%d\n", add(5, 3, 1));
return 0;
}
As macros don't expand recursively, the following is possible:
#define add(a, b, c) ( foo() , add((a), (b), (c)) )
The add in the replacement refers to the function, not the macro. This approach, however, has a few pitfalls: Taking the address and using a function pointer will refer to the real function, not the macro, as would enclosing add in parentheses as in (add)(a, b, c).
Sure you can define a macro
#define foo(a,b,c) {foo(); add(a,b,c);}
If C++ inline function is not an option then use comma operator:
#define bar(a, b, c) (foo(), add((a), (b), (c)))

How to have an array of functions that returns pointers of ints

When I try to compile the following line
int* x[](), (*y)();
I get the error "x declared as an array of functions of type int()"
You cannot really declare an array of functions, but you can have an array of function pointers, which will probably give you the same effect, because you can invoke them without explicit dereferencing.
The following will declare an array of 5 function pointers which return int*.
int* (*x[5])();
The website cdecl will let you play with various pointer declarations to see what they mean in English.
Here is the golden rule for reading C declarations, stolen from this old article.
Start at the variable name (or innermost construct if no identifier is
present. Look right without jumping over a right parenthesis; say what
you see. Look left again without jumping over a parenthesis; say what
you see. Jump out a level of parentheses if any. Look right; say what
you see. Look left; say what you see. Continue in this manner until
you say the variable type or return type.
When applied to the declaration above, we say:
x is an array of 5 pointers to functions returning pointer to int.
As SteveCox correctly commented below, we note that if we run into a type qualifier on the left hand side when following the above rule, it will describe the type to its left rather than its right. For example, the following declaration declares an array of 5 pointers to functions returning const pointer to int, not pointer to const int.
int* const (*x[5])();
Try this for an array of 2 function pointers.
#include <stdio.h>
int *first(void) { return NULL; }
int *second(void) { return NULL; }
int main(void) {
int *(*fx[2])(void);
fx[0] = first;
fx[1] = second;
/* ... */
if (fx[0]() == fx[1]()) {
printf("Calling both functions returns the same value.\n");
}
return 0;
}
A practical application might look like:
#include <ansi_c.h>
int add_(int, int);
int sub_(int, int);
int mul_(int, int);
int div_(int, int);
enum {
ADD,
SUB,
MUL,
DIV
};
int (*mathOps[4])(int, int);
int main(void)
{
int i;
mathOps[ADD]=add_;
mathOps[SUB]=sub_;
mathOps[MUL]=mul_;
mathOps[DIV]=div_;
for(i=ADD;i<=DIV;i++)
{
printf("results are: %d\n", mathOps[i](3, 3));
}
getchar();
return 0;
}
int add_(int a, int b)
{
return a + b;
}
int sub_(int a, int b)
{
return a - b;
}
int mul_(int a, int b)
{
return a * b;
}
int div_(int a, int b)
{
return a / b;
}

How to pass a macro as an argument in a C function?

I want to pass a macro as an argument in a C function, and I don't know if it possible.
I would like to see this operation, for instance:
I have these macros:
#define PRODUCT(A, B) ((A) * (B))
#define SUM(A, B) ((A) + (B))
And then I have this function with the following signature:
int just_a_function(int x, MACRO_AS_PARAMATER_HERE);
and then i want to call this function like:
just_a_function(10, SUM);
is it possible?
Thanks
You can't pass as function argument.
But if function is a macro this is possible.
#include <stdio.h>
#define PRODUCT(A, B) ((A) * (B))
#define SUM(A, B) ((A) + (B))
#define JUST_A_FUNCTION(A, B, MACRO) MACRO(A, B)
int main() {
int value;
value = JUST_A_FUNCTION(10, 10, SUM);
printf("%d\n", value);
value = JUST_A_FUNCTION(10, 10, PRODUCT);
printf("%d\n", value);
return 0;
}
You can't do that.
Use normal functions instead:
int sum(int x, int y)
{
return x+y;
}
//...
just_another_function(10, sum);
Note: just_another_function must accept int (*)(int, int) as the second argument.
typedef int (*TwoArgsFunction)(int, int);
int just_another_function(int x, TwoArgsFunction fun);
Hi what you are passing is macro means its a substitution your passing . Think about it ..
Ex : #define HIGH 1
In a function you can use int variable. So you can pass 1 to the function . In a function its stored as integer variable
Preprocessor directive works first . Once in a main macro are replaced means in the sense in a function you have to take care of the substitution. If I would have used Macro High 1 ,, in function I will take as int as a argument to get for local function stack. For better understanding check the topics 1.preprocessor directive 2. How the hex file created once you will compile
#include <stdio.h>
#define HIGH 1
#define LOW 0
void pin(int, int);
void pin(int a, int b) {
printf("A: %d B: %d\n", a, b);
}
int main() {
pin(1, HIGH);
return 0;
}
Compilation step involve:
pre processor directive
compiler
linker
executable file

Resources