# syntax in C (conversion?) [duplicate] - c

For example I have a macro:
#define PRINT(int) printf(#int "%d\n",int)
I kinda know what is the result.
But how come #int repersent the whole thing?
I kinda forget this detail. Can anybody kindely give me a hint?
Thanks!

In this context (applied to a parameter reference in a macro definition), the pound sign means to expand this parameter to the literal text of the argument that was passed to the macro.
In this case, if you call PRINT(5) the macro expansion will be printf("5" "%d\n", 5); which will print 5 5; not very useful; however if you call PRINT(5+5) the macro expansion will be printf("5+5" "%d\n", 5+5); which will print 5+5 10, a little less trivial.
This very example is explained in this tutorial on the C preprocessor (which, incidentally, is the first Google hit for c macro pound sign).

"#" can show the name of a variable, it's better to define the macro as this:
#define PRINT(i) printf(#i " = %d\n", i)
and use it like this:
int i = 5;
PRINT(i);
Result shown:
i = 5

That is a bad choice of name for the macro parameter, but harmless (thanks dreamlax).
Basically if i write like so
PRINT(5);
It will be replaced as
printf("5" "%d\n",5);
or
printf("5 %d\n",5);
It is a process called Stringification, #int is replaced with a string consisting of its content, 5 -> "5"

'#' is called a stringize operator.
Stringize operator puts quotes around the parameter passed and returns a string. It is only used in a marco statements that take the arguments.
#include<stdio.h>
#define stringLiteral(sl) #sl
int main()
{
char StringizeOpreator = 'a';
printf(stringLiteral(StringizeOpreator));
return 0;
}
Here the stringLiteral marco takes the formal argument sl and returns #sl. Actual argument passed is StringizeOpreator variable. The return statement #sl has # operator, that puts quotes around the argument like "StringizeOpreator" and returns a string.
So the output of the above program is the name of the actual parameter 'StringizeOpreator' rather than the value stored in the actual parameter passed.
output :
StringizeOperator
...
exitcode 0
To learn more visit this link:
Stringize Operator

Related

Argument counting in macro

I'm trying to understand the argument counting in C preprocessing macro and the idea in this answer. We have the following macro (I changed the number of arguments for simplicity):
#define HAS_ARGS(...) HAS_ARGS_(__VA_ARGS__, 1, 1, 0,)
#define HAS_ARGS_(a, b, c, N, ...) N
As far as I understand the purpose of this macro is to check if the given varargs empty. So on empty varargs the macro invokation is replaced with 0 which seems fine. But with a single argument it also turns into 0 which I seems strange.
HAS_ARGS(); //0
HAS_ARGS(123); //also 0
HAS_ARGS(1, 2); //1
LIVE DEMO
I think I understand the reason. In case of empty varargs a is replaced with empty preprocessing token, in case of a single argument vararg a is replaced with the argument yielding the same result.
Is there a way to get 0 returned in case varargs are empty, 1 in case argument number is from 1 to the defined in HAS_ARGS_ macro invokation without using comma-swallowing or other non-conforming tricks. I mean
SOME_MACRO_F() //0
SOME_MACRO_F(234) //1
SOME_MACRO_F(123, 132) //1
//etc
You cannot pass zero arguments to HAS_ARGS(...). ISO C (and C++, at least for the next two years) requires that an ellipsis corresponds to at least one additional argument after the last named one.
If there are no named ones, then the macro needs to be passed at least one argument. In the case of HAS_ARGS() the extra argument is simply an empty token sequence. Zero arguments is simply not possible.
This is exactly the use case in the answer. The target macro expects at least one argument. So we can use a wrapper accepting only an ellipsis for "overload resolution". A better name probably would have been HAS_MORE_THAN_1_ARGS. Because that's what the predicate is meant to tell you. Alas, I favored brevity on that answer.
It seems difficult to compute that at compile-time, but you can do it at run-time by stringifying the arguments and testing if the string is empty.
Tested with gcc:
#include <stdio.h>
#define HAS_ARGS(...) (#__VA_ARGS__[0] != '\0')
int main()
{
printf("%d %d %d %d\n",HAS_ARGS(),HAS_ARGS(10),HAS_ARGS(20,"foo"),HAS_ARGS(10,20));
return 0;
}
this prints:
0 1 1 1
behind the scenes, here's what the pre-processor outputs:
int main()
{
printf("%d %d %d %d\n",(("")[0] != '\0'),(("10")[0] != '\0'),(("20,\"foo\"")[
0] != '\0'),(("10,20")[0] != '\0'));
return 0;
}

How to pass value in #define directives in c?

I want to pass value in #define directives. I am new to c programming. For example we use %s or % d in printf function printf("hello %d",into); how can I use same in # define directives.my code is #define URL "www.my website.com" I am trying to pass value using following code #define URL "my website.com%d", int but I am getting no result
You can use Macro arguments:
#include <stdio.h>
#define URL(i) "www.mywebsite.com"#i
int main() {
printf(URL(5)); // Will print www.mywebsite.com5
return 0;
}
# is called the pasting operator. It pastes two tokens together.
OR you can do this...
#include <stdio.h>
#define URL(i) "www.mywebsite.com %d", i
int main() {
printf(URL(5));
return 0;
}
Difference:
In the 1st solution, the pre-processor simply pastes any value of i with "www.mywebsite.com". It doesn't necessarily have to be data. It can be anything.
If you pass in URL(ABC) (Note: ABC is not a string. It is without quotes. It is just a simple token.), your output will be www.mywebsite.comABC.
If you pass in URL("ABC") ("ABC" with quotes), you output will be www.mywebsite.com"ABC".
So in short, it doesn't matter what you pass, pre-processor doesn't care about the data-type. It treats it just as a simple token and pastes it with www.mywebsite.com. Here your "ABC" wasn't treated as a String by pre-processor but as any other token.
In the 2nd solution, the pre-processor doesn't do any pasting. It simply evaluates your printf statement as, printf("www.mywebsite.com%d", i). So you will need to pass in an integer as URL(5) or any other integer apart from 5. If you pass data of any other datatype, it will give you a warning. You can't pass URL(ABC). It will give an error. Because ABC is not data. But if you pass "ABC" as a string(i.e, with quotes), it will give a warning but your code will compile and result output would be www.mywebsite.com96882598

What does #x inside a C macro mean?

For example I have a macro:
#define PRINT(int) printf(#int "%d\n",int)
I kinda know what is the result.
But how come #int repersent the whole thing?
I kinda forget this detail. Can anybody kindely give me a hint?
Thanks!
In this context (applied to a parameter reference in a macro definition), the pound sign means to expand this parameter to the literal text of the argument that was passed to the macro.
In this case, if you call PRINT(5) the macro expansion will be printf("5" "%d\n", 5); which will print 5 5; not very useful; however if you call PRINT(5+5) the macro expansion will be printf("5+5" "%d\n", 5+5); which will print 5+5 10, a little less trivial.
This very example is explained in this tutorial on the C preprocessor (which, incidentally, is the first Google hit for c macro pound sign).
"#" can show the name of a variable, it's better to define the macro as this:
#define PRINT(i) printf(#i " = %d\n", i)
and use it like this:
int i = 5;
PRINT(i);
Result shown:
i = 5
That is a bad choice of name for the macro parameter, but harmless (thanks dreamlax).
Basically if i write like so
PRINT(5);
It will be replaced as
printf("5" "%d\n",5);
or
printf("5 %d\n",5);
It is a process called Stringification, #int is replaced with a string consisting of its content, 5 -> "5"
'#' is called a stringize operator.
Stringize operator puts quotes around the parameter passed and returns a string. It is only used in a marco statements that take the arguments.
#include<stdio.h>
#define stringLiteral(sl) #sl
int main()
{
char StringizeOpreator = 'a';
printf(stringLiteral(StringizeOpreator));
return 0;
}
Here the stringLiteral marco takes the formal argument sl and returns #sl. Actual argument passed is StringizeOpreator variable. The return statement #sl has # operator, that puts quotes around the argument like "StringizeOpreator" and returns a string.
So the output of the above program is the name of the actual parameter 'StringizeOpreator' rather than the value stored in the actual parameter passed.
output :
StringizeOperator
...
exitcode 0
To learn more visit this link:
Stringize Operator

Why one needs two brackets to use macros in C?

KdPrint(("Enter HelloWDMAddDevice\n"));
What's the reason for doing that?
That is so you can pass an entire argument list to the macro and have it pass it on to a function that takes a variable number of arguments.
I would bet anything that the definition of that macro is:
#if DEBUG /* or something like it */
#define KdPrint(args) (printf args)
#else
#define KdPrint(args) /* empty */
#endif
Or similar to some other function that works just like printf.
If it were defined as printf(args), then you could only pass the single string argument, because an argument to a macro can't contain a comma that isn't inside a nested parenthesis.
It causes everything inside the parens to be treated as a single parameter to the macro. In the example shown, it can allow for varargs types of parameters:
KdPrint(( "My info is %s\n", "my name" ));
As well as
KdPrint(( "fn %s ln %s\n", "my", "name" ));
If the macro in question was not well written using parentheses, it might be necessary because of operator precedence. Take this macro for example:
#define MY_MACRO(a) a * 11
Well, if you did this:
int b = MY_MACRO(1 + 2);
b, instead of being 33 like it should, would actually be replaced with int b = 1 + 2 * 11 which is 23 and not 33. If your macro isn't written like that, though (without parenthesis around the a) then it's unnecessary.
If this is the KdPrint() that you are talking about, then this is because you can use KdPrint() macro with format arguments, and it is not a variable length macro.
For example, you can do:
KdPrint(("The answer is %d\n", 42));
and so on.
For your specific example, I cannot tell you, because I don't know what is XdPrint.
But in a more general case, it is because a macro I just like a search and replace. Suppose you have:
#define MULT(a,b) (a*b)
If you call MULT(1+1, 2+2), it would become 1+1*2+2, and result as 5 instead of 8 as you would expect. Doing MULT((1+1), (2+2)) would gives you the expected result. That is why you need to double the brackets.

Why does my C program output this?

I am trying to solve two Preprocessor related questions but in both programs I am getting results that I am not able to figure out how. Below is my program:
#include<stdio.h>
#define SQUARE(x) x*x
int main()
{
float s=10,u=30 ,t=2,a;
a=2*(s-u*t)/SQUARE(t);
printf("Result:%f\n",a);
return 0;
}
According to me, the output of this programme should be -25.000 but I am getting -100.000.
And in second program:
#define FUN(i,j) i##j
int main()
{
int val1 = 10;
int val12 = 20;
clrscr();
printf("%d\n",FUN(val1,2));
getch();
}
Output should be 102 but I am getting 20;
why is it so?
#define SQUARE(x) x*x
should be
#define SQUARE(x) ((x)*(x))
Indeed, without the parentheses, 2*(s-u*t)/SQUARE(t) is expanded as
2*(s-u*t)/t*t
which is interpreted as
(2*(s-u*t)/t)*t
As to your second problem, FUN(val1,2) will get expanded as val12 per the semantics of the ## operator. It is still not clear what your intent is: the printf line will be understood as
printf("%d\n", val12);
which will print 20.
the first one:
a=2*(s-u*t)/SQUARE(t);
after replacing the define we get:
a=2*(s-u*t)/t*t;
now, since we don't have () in the definition of SQUARE we get:
a=2*(10-30*2)/2*2; --> a=2*(-50)/2*2; --> a=-100/2*2; --> a=-50*2; --> a=-100
if you want to get -25 you should define SQUARE(x) as (x*x).
Edit : add explanation regarding the second example.
printf("%d\n"FUN(val1,2));
once again, we first should replace the define (reminder: ## "concatenates" the string of the define - I can't find the perfect words in order to explain it so just take a look at the example...):
printf("%d\n",val12); [note: the comma (,) is missing - so it won't compile.]
since the value of val12 is 20 that's what you'll get.
the point of those 2 examples is to remember that we should always deal with the defines first (since in "real life" the compiler (or pre-processor) does it before the run time)
I hope it helps..
For the first case,
a=2*(s-u*t)/SQUARE(t);
would translate to
a=2*(s-u*t)/t*t;
at compile time. This is a common mistake made with preprocessors.
i know i am late, but i am having the perfect answer.
in c # at define is used to call the text as it is in the function parameter,
example, #define hai(s1) printf("%s=%s",#s1,s1);
in main: i am calling as hai(tom); tom was initialized as "india" string.
the output for this is tom=india, the calling string tom is printed by help of #.
similarly ## is used to take the text from function argument and join them and return the value of the joined identifier.
the above program has two argument va1 and 2. passed to i and j. then va1 and 2 is joined. and form va12.
va12 is the identifier available with value 20. that's why 20 is returned.

Resources