C/C++ preprocessor single quote? [duplicate] - c-preprocessor

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to single-quote an argument in a macro?
How can it do the following:
#define MACRO(X) ...
MACRO(a) // should give 'a'

I might be missing an easier way, but how about #define MACRO(X) ((#X)[0]). The # stringtizes X and then [0] selects the first character.

Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:
There is no way to convert a macro
argument into a character constant.

Like this:
#include <string>
std::string Macro(const std::string& s)
{
std::string ret = "'";
ret += s;
ret += "'";
return ret;
}
EDIT:
I posted this answer before it was revealed that this was needed for metaprogramming. I don not know of a way to accomplish this for metaprogramming, but metaprogramming is not my forte.
Also, as for why I am effectively saying "don't use the preprocessor" in the first place, read the comments below. But in short, I believe that almost everything that is commonly done using the preprocessor can and should be done using first-level constructs instead. Using the preprocessor skirts the C++ type system and reduces safety. Macros are difficult to debug, difficult to extend. Extensively using macros will result in code that isn't familiar to the programmers who didn't create the macro, resulting in a kind of "secret language" only 1 person knows, decreasing maintainability of not only the macros, but the functions where they are used.
OK, I guess that wasn't so short, but there it is.

Related

Define custom syntax "until" in C

I expect I can do something like this:
int i = 0;
until (i == 2){
printf("yes\n");
i++;
}
Without telling detail about what until does, I'm sure reader know what is the algorithm from code above. Yes I know I can just use while(!condition){}.
The output will be:
yes
yes
So is it possible that I can achieve my goal?
I feel macro able to do this with define or something else. But I'm lack of knowledge about preprocessing directive syntax in C
#define until <what should I fill here>
Edit:
Many people triggered from what am I doing. I'm sorry for if I bother you guys. Don't worry, this syntax is just for my self only. So I hope I don't bother code reader who accidentally read my code or C priest.
First of all, and I can't stress this enough: making your own secret, private language using function-like macros is a cardinal sin in C. It is perhaps the worst thing you can ever do.
Why? Because other people reading your code are expected to know C. They are however not expected to know your secret private macro language. Furthermore, they have absolutely no interest in learning your secret private macro language.
So please never do things like this in real programs.
That being said, you pretty much already answered the question yourself:
#define until(condition) while(!(condition))
Note that condition, being a function-like macro parameter, should be placed inside a parenthesis. This prevents accidental operator precedence bugs. For example if the caller passes until(i + 1) then you want it to loop while(!(i+1)) and not while(!i + 1).
From Expert C Programming:
Macro use is best confined to naming literal constants,
shorthand for a few well-chosen constructs. Define the macro name all
in capitals so that, in use, it's instantly clear it's not a function
call. Shun any use of the C preprocessor that modifies the underlying
language so that it's no longer C.
Re: "I'm sure reader know what is the algorithm from code above."
No, it would confuse one even more as the keyword until is not part of the C language. It doesn't take much to type a few extra characters.
That being said, you could do:
#define until(condition) while(!(condition))
Compile your program with:
gcc -E -nostdinc main.c
to see what changes the preprocessor made.
But it would still be an abomination, and not something one would condone.
Using until is useful in select cases.
Sometimes an algorithm or software contract uses until in its definition, so it is good to see that match in code.
Yet re-writing language semantics adds confusion and maintenance costs.
Consider a comment when until is needed.
int i = 0;
// until (i == 2) {
while (i != 2) {
printf("yes\n");
i++;
}
Yes, you can use define for that. See the following example for the macro definition
#include <stdio.h>
#define until(x) while(!(x))
int main() {
int i = 0;
until (i == 2){
printf("iteration %d\n", i);
i++;
}
return 0;
}
If you run it, the output would be
iteration 0
iteration 1
I don't know why you would do this, until is a mostly abandoned keyword for a reason. But this should work:
#define until(cond) while (!(cond))

C syntax: character combinations valid in any context

Here's a formal grammar brain teaser (maybe :P)
I'm fairly certain there is no context where the character sequence => may appear in a valid C program (except obviously within a string). However, I'm unable to prove this to myself. Can you either:
Describe a method that I can use for an arbitrary character sequence to determine whether it is possible in a valid C program (outside a string/comment). Better solutions require less intuition.
Point out a program that does this. I have a weak gut feeling this could be undecidable but it'd be great if I was wrong.
To get your minds working, other combos I've been thinking about:
:- (b ? 1:-1), !? don't think so, ?! (b ?!x:y), <<< don't think so.
If anyone cares: I'm interested because I'm creating a little custom C pre-processor for personal use and was hoping to not have to parse any C for it. In the end I will probably just have my tokens start with $ or maybe a backquote but I still found this question interesting enough to post.
Edit: It was quickly pointed out that header names have almost no restrictions so let me amend that I'm particularly interested in non-pre-processor code, alternatively, we could consider characters within the <> of #include <...> as a string literal.
Re-edit: I guess macros/pre-processor directives beat this question any which way I ask it :P but if anyone can answer the question for pure (read: non-macro'd) C code, I think it's an interesting one.
#include <abc=>
is valid in a C program. The text inside the <...> can be any member of the source character set except a newline and >.
This means that most character sequences, including !? and <<<, could theoretically appear.
In addition to all the other quibbles, there are a variety of cases involving macros.
The arguments to a macro expansion don't need to be syntactically correct, although of course they would need to be syntactically correct in the context of their expansion. But then, they might never be expanded:
#include <errno.h>
#define S_(a) #a
#define _(a,cosmetic,c) [a]=#a" - "S_(c)
const char* err_names[] = {
_(EAGAIN, =>,Resource temporarily unavailable),
_(EINTR, =>,Interrupted system call),
_(ENOENT, =>,No such file or directory),
_(ENOTDIR, =>,Not a directory),
_(EPERM, =>,Operation not permitted),
_(ESRCH, =>,No such process),
};
#undef _
const int nerr = sizeof(err_names)/sizeof(err_names[0]);
Or, they could be used but in stringified form:
#define _(a,b,c) [a]=#a" "S_(b)" "S_(c)
Note: Why #a but S_(c)? Because EAGAIN and friends are macros, not constants, and in this case we don't want them to be expanded before stringification.
/*=>*/
//=>
"=>"
'=>'

C macros: advantage/intent of apparently useless macro

I have some experience in programming in C but I would not dare to call myself proficient.
Recently, I encountered the following macro:
#define CONST(x) (x)
I find it typically used in expressions like for instance:
double x, y;
x = CONST(2.0)*y;
Completely baffled by the point of this macro, I extensively researched the advantages/disadvantages and properties of macros but still I can not figure out what the use of this particular macro would be. Am I missing something?
As presented in the question, you are right that the macro does nothing.
This looks like some artificial structure imposed by whoever wrote that code, maybe to make it abundantly clear where the constants are, and be able to search for them? I could see the advantage in having searchable constants, but this is not the best way to achieve that goal.
It's also possible that this was part of some other macro scheme that either never got implemented or was only partially removed.
Some (old) C compilers do not support the const keyword and this macro is most probably a reminiscence of a more elaborate sequence of macros that handled different compilers. Used like in x = CONST(2.0)*y; though makes no sense.
You can check this section from the Autoconf documentation for more details.
EDIT: Another purpose of this macro might be custom preprocessing (for extracting and/or replacing certain constants for example), like Qt Framework's Meta Object Compiler does.
There is absolutely no benefit of that macro and whoever wrote it must be confused. The code is completely equivalent to x = 2.0*y;.
Well this kind of macro could actually be usefull when there is a need to workaround the macro expansion.
A typical example of such need is the stringification macro. Refer to the following question for an example : C Preprocessor, Stringify the result of a macro
Now in your specific case, I don't see the benefit appart from extreme documention or code parsing purposes.
Another use could be to reserve those values as future function invocations, something like this:
/* #define CONST(x) (x) */
#define CONST(x) some_function(x)
// ...
double x, y;
x = CONST(2.0)*y; // x = some_function(2.0)*y;
Another good thing about this macro would be something like this
result=CONST(number+number)*2;
or something related to comparisons
result=CONST(number>0)*2;
If there is some problem with this macro, it is probably the name. This "CONST" thing isn't related with constants but with some other thing. It would be nice to look for the rest of the code to know why the author called it CONST.
This macro does have the effect of wrapping parenthesis around x during the macro expansion.
I'm guessing someone is trying to allow for something along the lines of
CONST(3+2)*y
which, without the parens, would become
3+2*y
but with the parens becomes
(3+2)*y
I seem to recall that we had the need for something like this in a previous development lifetime.

What are legitimate uses for function-like macros? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
There is no shortage of examples of bad or dangerous function-like macros in C/C++.
#define SQUARE(x) x * x
printf("%d", SQUARE(4)); //16
printf("%d", SQUARE(3+1)); //7
#undef SQUARE
#define SQUARE(x) (x) * (x)
printf("%d", 36/4); //9
printf("%d", SQUARE(6)/SQUARE(2)); //36
#undef SQUARE
#define SQUARE(x) ((x) * (x))
int x = 3;
++x;
printf("%d", SQUARE(x)); //16
int y = 3;
printf("%d", SQUARE(++y)); //?
#undef SQUARE
Given the problems with function-like macros, what examples are there of good/prudent/recommended uses for them?
Are there any times when a function-like macro would be preferrable to a function?
I imagine there must be some really good cases of this, or else the preprocessor makers would have made their job easier and left them out.
The comments have captured most of it.
Some types of debugging and instrumentation can be accomplished only by use of a function-style macro. The best example is assert(), but function-style macros can also be used for instrumenting code for profiling as well. Magic macros like __FILE__ and __LINE__ as well as features like # for quoting and ## for token-pasting make function-like macros valuable for the debugging and profiling.
In C++, with templates and typically more aggressive inlining, there are few, if any, other reasons to use a function-style macro. For example, the template function std::max is a much better solution than a MAX macro for the reasons illustrated in the question.
In C, it's sometimes necessary in optimization to ensure the a small piece of code is inlined. Macros, with all their caveats, are still occasionally useful in this context. The ALLCAPS naming convention is there to warn programmers that this is actually a macro and not a function because of all the problems with simple text substitution. For example, if you had several places where you needed the equivalent of std::max in a performance-critical piece of code, a macro--with all its dangers--can be a useful solution.
Most of the time you don't need to use macros. However there are some cases that are legitimate (although there is room for discussion).
You should not use macros when you can use enums. You should not have macros that depend on having a local variable with a magic name. You should not have macros that can be used as l-values. You should not have macros that have side effects on the code around the expanded macro. Using macros instead of inline functions is most of the time a bad idea, in any case the list is endless.
You could use a macro to fake an iterator though, in C and in particular the Linux Kernel you will see the following:
#define list_for_each_safe(pos, n, head) \
for (pos = (head)->next, n = pos->next; pos != (head); \
pos = n, n = pos->next)
There are numerous other similar type of macros that are used throughout the Linux kernel source.
Also offsetof(3) is typically implemented as a macro, as well as assert(3) etc.
I generally agree with dmp here. If you can use something else you use it and forget about macros.
That said I will mostly repeat what's in comments:
You usually need function like macro when you need to use inside it some other preprocessor symbols (__LINE__, __FILE__, __func__ and so on). This usually means assert/debugging macros.
Stringizing / pasting tokens (# and ## operators) in a macro.
You CAN (if you feel adventures enough) use function-like macros to create enum->string mappings using some cleaver tricks like defining/undefining and redefining macros.
Something like va_list/va_arg where you need access through pointer with simultaneous change of the place where it points to.
And I repeat myself - if you can avoid preprocessor just do that.
The C standard has (or allows) a whole bunch of them, and I think anything that does macros in the same spirit should be legitimate:
character handling functions isspace and similar are often implemented as macros
CMPLX is declared to be a macro
UINT64_C and similar are macros
if you include tgmath.h, sin, cos and a lot of other functions become macros
the whole point of the new _Generic keyword is to write function-like macros
In some cases, there will be compiler specific instructions which vary and are noisy to rewrite for each compiler. One macro that I use often which falls into this category is used to inform the compiler that a parameter is unused:
virtual size_t heightForItemAtIndex(const size_t& idx) const {
MONUnusedParameter(idx); // << MONUnusedParameter() is the macro
return 12; // << this type's items are all the same height
}
The problem is introduced better here: cross platform macro for silencing unused variables warning
Google Style C++ Guide has one example of a pretty useful macro (I'm not sure if this is what you mean by 'function-like macro' - it takes an argument but it can not be replaced by a function call):
DISALLOW_COPY_AND_ASSIGN(ClassName);
Such macro can be put in a private section of a class to disable a copy constructor and an assignment operator that are automatically generated by a compiler. It is usually a good idea to disallow these two automatically generated methods unless a class really needs them. Without a macro disabling requires quite a lot of typing in every class:
ClassName(const ClassName&);
void operator=(const ClassName&);
The macro just automatically generates this code. This is pretty safe. I'm not aware of any cases in which such macro causes problems.

#define statement explained

gcc 4.4.1
I am maintaining someone's code and I have come across something that I don't understand.
#define RES_API(name, func) name##_##func
Can anyone explain?
Many thanks,
The ## is a concatenation operator. Using RES_API(name1, func1) in your code would be replaced with name1_func1. More information here.
The ## operator concatenates two tokens. In your case, name is appended with an underscore, and that is appended with func.
So RES_API(aName, aFunc) results in aName_aFunc.
By itself, it seems rather annoying. I could see a use when mixing C and C++ code, as C libraries tend to prefix their functions, while C++ libraries would place them in a namespace.
Given an alternate definition, such as:
#define RES_API(name, func) name##::##func
You suddenly have a generic way to switch between a C interface, or C++.
I know you've already got your answer, but there is some great info on the C-FAQ which explains allot of the C Preprocessor magic.
Instead of doing OBJ_DoSomething, with this macro you can do RES_API(OBJ, DoSomething). Personally I think its silly.

Resources