In a generated piece of c code I found something like this (edited):
#include <stdio.h>
int main() {
(void) (
{
int i = 1;
int y = 2;
printf("%d %d\n", i,y);
}
);
return 0;
}
I believe I have never seen the construct (void) ( { CODE } ) before, nor am I able to figure out what the purpose might be.
So, what does this construct do?
({ }) is a gcc extension called a statement expression.
http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
A statement expression yields a value and the (void) cast is probably here to remove the compiler warning or to make explicit that the value of the statement expression is not used.
Now (void) ({ }) is the same as a simple compound statement {} and there is no point of using it.
One application of ({ }) is the ability to replace expressions with code blocks. In this way very complex macros can be embedded in to expressions.
#define myfunc() { } // can be a typical way to automatize coding. e.g.
myfunc(x,y,z);
myfunc(y,x,z);
myfunc(x,z,y); // would work to eg. unroll a loop
int a = myfunc()*123; // but this wouldn't work
Instead
#define myfunc(a,b,c) ({printf(a#b#c);})
int a= myfunc(a,b,c) * 3; // would be legal
Related
This questions is about my homework.
This topic is need to use like:
#define GENERIC_MAX(type)\
type type##_max(type x, type y)\
{\
return x > y ? x : y;\
}
The content of the question is to make this code run normally:
#include <stdio.h>
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
The result of the operation is like this:
i=5.2000
j=3
And this code is my current progress, but there are have problems:
#include <stdio.h>
#define printname(n) printf(#n);
#define GenerateShowValueFunc(type)\
type showValue_##type(type x)\
{\
printname(x);\
printf("=%d\n", x);\
return 0;\
}
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
I don’t know how to make the output change with the type, and I don’t know how to display the name of the variable. OAO
This original task description:
Please refer to ShowValue.c below:
#include <stdio.h>
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
Through [GenerateShowValueFunc(double)] and [GenerateShowValueFunc(int)] these two lines macro call, can help us to generated as [showValue_double( double )] and [showValue_int( int )] function, And in main() function called. The execution result of this program is as follows:
i=5.2000
j=3
Please insert the code that defines GenerateShowValueFunc macro into the appropriate place in the ShowValue.c program, so that this program can compile and run smoothly.
A quick & dirty solution would be:
type showValue_##type(type x)\
{\
const char* double_fmt = "=%f\n";\
const char* int_fmt = "=%d\n";\
printname(x);\
printf(type##_fmt, x);\
return 0;\
}
The compiler will optimize out the variable that isn't used, so it won't affect performance. But it might yield warnings "variable not used". You can add null statements like (void)double_fmt; to silence it.
Anyway, this is all very brittle and bug-prone, it was never recommended practice to write macros like these. And it is not how you do generic programming in modern C. You can teach your teacher how, by showing them the following example:
#include <stdio.h>
void double_show (double d)
{
printf("%f\n", d);
}
void int_show (int i)
{
printf("%d\n", i);
}
#define show(x) _Generic((x),\
double: double_show, \
int: int_show) (x) // the x here is the parameter passed to the function
int main()
{
double i = 5.2;
int j = 3;
show(i);
show(j);
}
This uses the modern C11/C17 standard _Generic keyword, which can check for types at compile-time. The macro picks the appropriate function to call and it is type safe. The caller doesn't need to worry which "show" function to call nor that they pass the correct type.
Without changing the shown C-code (i.e. only doing macros), which I consider a requirement, the following code has the required output:
#include <stdio.h>
#define showValue_double(input) \
showValueFunc_double(#input"=%.4f\n" , input)
#define showValue_int(input) \
showValueFunc_int(#input"=%d\n" , input)
#define GenerateShowValueFunc(type) \
void showValueFunc_##type(const char format[], type input)\
{\
printf(format, input); \
}
/* ... macro magic above; */
/* unchangeable code below ... */
GenerateShowValueFunc(double)
GenerateShowValueFunc(int)
int main()
{
double i = 5.2;
int j = 3;
showValue_double(i);
showValue_int(j);
}
Output:
i=5.2000
j=3
Note that I created something of a lookup-table for type-specific format specifiers. I.e. for each type to be supported you need to add a macro #define showValue_ .... This is also needed to get the name of the variable into the output.
This uses the fact that two "strings" are concatenated by C compilers, i.e. "A""B" is the same as "AB". Where "A" is the result of #input.
The rest, i.e. the required function definition is very similar to the teacher-provided example, using the ## operator.
Note, this is if the variable name has to correctly be mentioned in the output.
With out the i = things would be easier and would more elegantly use the generated functions WITHOUT having the called showValue_double(i); be explicit macros. I.e. the functions generated are 1:1 what is called from main(). I think that might be what is really asked. Let me know if you want that version.
I use the const for assigning the variable but the array shows an error "variable-sized object may not be initialized"
#include <stdio.h>
int main()
{
const int city=10;
const int week=2;
int arr[city][week]={34,34,64,23,65,22,65,77,42,74,22,88,46,34,77,53,63,457,234,723};
for(int i=0;i<city;i++)
{
for(int j=0;j<week;j++)
{
printf("%d",arr[city][week]);
}
}
}
You are using const qualified variables for your array dimension and not "integer constant expressions". For C, this means that your array is a variably modified type, for which C does not allow initializers.
As others already told you, if initialization would be allowed, the syntax has to be = and not ==.
You have several issues.
you've posted it in the subject, is that you can't use const int for the array length and then initialize it, because it will become a variable-sized object, and you can't initialize it in with constant numbers. You can use #ifdef to define city/week, and then it will not happen.
You've used compare (==) instead of assignment (=)
change:
int arr[city][week]=={34,34,64,23,65,22,65,77,42,74,22,88,46,34,77,53,63,457,234,723};
to:
int arr[city][week]={34,34,64,23,65,22,65,77,42,74,22,88,46,34,77,53,63,457,234,723};
you need to change your printf and probably add line break:
printf("%d\n",arr[i][j]);
so to summarize:
#include <stdio.h>
#define city 10
#define week 2
int main()
{
int arr[city][week]={34,34,64,23,65,22,65,77,42,74,22,88,46,34,77,53,63,457,234,723};
for(int i=0;i<city;i++)
{
for(int j=0;j<week;j++)
{
printf("%d\n", arr[i][j]);
}
}
}
== compares, = assigns
you even would print the same output
i would also prefer to use {a,b},{c,d}...
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.
I've got a bunch of C functions which get assigned to an array of function pointers, along the lines of this:
typedef int (*func)(int);
int SomeLongName1(int a) {
// ...
}
// ...
int SomeLongName1000(int a) {
// ...
}
func f[] = { SomeLongName1, ... , SomeLongName1000 };
This is a lot of work to create and is prone to errors. For instance, there could be a typo in the function name such that a valid function is still named, but the wrong one. Or, if a new function is added at the end one could forget to go in and explicitly add it to the list of function pointers as well.
In order to avoid having to explicitly declare the array of function pointers I have tried various tricks such as macros, which make the code hard to understand and require knowing how the macro works, and I am generally unsatisfied with them.
What I would like to do is something like this:
typedef int (*func)(int);
func f[] = {
int SomeLongName1(int a) {
// ...
}
// ...
int SomeLongName1000(int a) {
// ...
}
};
This way, the array would be automatically created, and if there was some way to put a null pointer at the end so I can determine how many function pointers there are that would be great as well.
However, the above isn't valid C and I'm coming up empty with any way of accomplishing this. If it is something compiler specific (e.g. a GCC extension) that would be ok.
All the functions are statically known at compile time, so I would like to avoid having to do any run-time initialization of the function pointer array - not that I have found a method to do it that way either.
This related question How to define an array of functions, seems to ask the same question, but does not carry it to its logical conclusion. Specifically, I don't want to have to re-type anything I have already typed so as to save time and avoid errors.
If you don't care about the order of functions in the array, and are willing to use a GCC extension, then you can achieve what you want using a whole bunch of initializer (constructor) functions. This obviously isn't ideal because of the sheer number of extra functions defined, but it is certainly one approach you can consider. It constructs the array at runtime.
Define the function append to append a single function to an array (reallocating if needed). Then, the code is basically
#define ARRAYFUNC(name) int name(int); \
void __attribute__((constructor)) __init_##name(void) { append(func); } \
int name(int a)
ARRAYFUNC(func1) {
...
}
ARRAYFUNC(func2) {
...
}
You could use the C preprocessor (X-Macros) for this:
#include <stdio.h>
// define a list of function names and bodies
#define FUNCS \
FUNC(add, { return a+b; }) \
FUNC(mul, { return a*b; }) \
FUNC(div, { return a/b; })
// let the preprocessor make up the actual function implementations
#define FUNC(name, body) int name(int a, int b) body
FUNCS
#undef FUNC
typedef int (*func)(int, int);
// let the preprocessor populate the array of function pointers
func f[] = {
#define FUNC(name, body) name,
FUNCS
#undef FUNC
};
// use it:
int main () {
int a = 2, b = 3, i = 0;
for (; i < sizeof(f)/sizeof(*f); i++) {
printf("%d\n", f[i](a,b));
}
return 0;
}
The output is:
$ gcc test.c && ./a.out
5
6
0
What I would use to solve such a situation (only if I can't avoid it, of course), is to use preprocessing. Not the one available from the C preprocessor, it does not provide the required functionality in a sensible syntax, but a really powerful one like m4.
With m4, your code could look like this:
define(`functionList', `, 0')
define(`functionArrayMember', `define(`functionList', `$1, 'FunctionList)$1')
define(`buildFunctionArray', `{ functionList }')
int functionArrayMember(SomeLongName1)(int a) {
return a+1;
}
//...
int functionArrayMember(SomeLongName1000)(int a) {
return a+1;
}
func f[] = buildFunctionArray();
You just need to provide the right m4 definition for functionArrayMember() and buildFunctionArray(), and you have the functionality you need.
I do not think there is any other way of doing what want to do.
What you wrote
func f[] = { SomeLongName1, ... , SomeLongName1000 };
already does what is best.
Maybe you could name your functions with an prefix 0000 to 1000, so that you can be sure each function is in the right place in your functions pointer array.
Also, if you really have 1000 different functions, they are surely things in common that could lead you to sort them in several arrays, reducing the numbering effort, and that is less error prone.
A friend told me there is a way to check with printf without modifying the original void function.
But I can't see how you can do it.
#include<stdio.h>
void test()
{
int a = 1;
int b = a;
}
main()
{
printf("%d",test());
}
I kept getting
error: invalid use of void expression
Is there a way to do it?
I see from your edit that you want to do this without modifying the function. You can employ the comma operator to make the function call in a printf:
#include <stdio.h>
void test()
{
int a = 1;
int b = a;
}
main()
{
printf("%d\n", (test(), 0));
// or even this, to be more explicit:
printf("%s\n", (test(), "test() was called."));
}
The comma operator evaluates the first operand - in this case your function call - and discards the result, then evaluates the second operand and the result is the result of the entire expression.
An example would be to pass memory pointer into the void function and fill it with data you need to see if your void function worked.
void
test_funtion(bool *answer)
{
answer = false;
// do stuff
if(error happens)
return;
answer = true;
return;
}
I don't see how you would use printf to let the program know.
Only way you would use printf for visual logging for yourself, but not the machine.