#define TYPE char *
if TYPE is char *
do A
if TYPE is int
do B
Is there an example how to do such things?
C preprocessor MACROS manipulate text, so are essentially typeless, so NO you can't do that.
You could associate another symbol with it:
#define TYPE char *
#define TYPE_IS_CHAR_STAR
#ifdef TYPE_IS_CHAR_STAR
...
#endif
You just need to keep them consistent manually.
Note that that's a dangerous macro; you should use a typedef instead. With the macro:
TYPE x, y;
x is a pointer, but y isn't.
You can get a similar effect by defining another macro along with the type, and using #ifdef etc. with that other macro. For example:
#define TYPE char *
#define TYPE_IS_PCHAR 1
...then later...
#ifdef TYPE_IS_PCHAR
do A
#endif
#ifdef TYPE_IS_INT
do B
#endif
It's not quite the same thing, but it still gets you there.
Not easily. You could do something like:
#define TYPE_IS_CHARPTR
//#define TYPE_IS_INT
#ifdef TYPE_IS_CHARPTR
do A
#endif
#ifdef TYPE_IS_INT
do B
#endif
But you really should be trying to minimise your use of the preprocessor for tricky things (anything other than simple variables).
With enumerated constants and inline functions, there's little need for such uses nowadays.
It would work if you just used basic types (since they're just strings - see Mitch's answer). But as soon as you try to use pointers, it won't work any more - the asterisk throws the preprocessor for a loop:
[holt#Michaela ~]$ gcc test.c
test.c:3:10: error: operator '*' has no right operand
But if you want do do different things based on different types, I'm going to have to recommend switching to C++ and using templates and template specialization. Reluctantly, since template syntax is incredibly ugly, but you should be able to do whatever you want.
Hope that helps!
Related
I'm trying to do something like the following:
//Bad; can't redefine macros; uses later definition.
#define foo )
#define foo(arg) ,arg)
That is, I want foo (note: not a macro function) to map to one thing, and I want the macro function foo(arg) to map to something else. So foo needs to be some #define constant (catching both cases) that maps onto . . . something.
I haven't been able to figure out a way, (and since this is a macro and a constant, the many previous questions do not apply). How can I do this?
Evil compiler-/platform-specific options are great too. Tagging this c for C-macros, although I'm using C++14.
Sidenote (by request): this could be used for e.g. making your own debug overloads for new that would work with placement new as well:
#define new new(__FILE__,__LINE__ foo
//...
void const* p1 = new int();
void const* p2 = new (ptr) int();
You seem to be looking for a preprocessor that has different name spaces for function- (with arguments) and object-like (plain #defines) macros - I don't know of any that would have that, and it would be fundamentally confusing if there was one, I assume.
I understand you want something like (note this is actually not trying to provide a solution)
// NOTE: Example might work in some very trivial use cases
#ifdef DEBUG
#define new(x) new(x);lognew(__FILE__,__LINE__)
#define pnew(p,x) new (p) (x); lognew(__FILE__,__LINE__)
#else
#define new(x) new(x)
#define pnew(p,x) new(p) (x)
#endif
And pnew and new should use the same keyword. No, I don't think that is possible (and I'm glad it isn't ;) ).
Functions with variable signatures are only allowed in C++ , called "function overloading".
After reading through some of K&R's The C Programming Language I came across the #define symbolic constants. I decided to define...
#define INTEGER_EXAMPLE 2
#define CHAR_EXAMPLE 2
...so my question is how does C know if I'm defining an int or a char type?
#define-d names have no types. They just define textual replacements.
What the compiler is seeing is the preprocessed form. If using GCC, try gcc -C -E somesource.c and have a look at the (preprocessed) output.
In the 1980s the preprocessor was a separate program.
Read about the cpp preprocessor, and preprocessor and C preprocessor wikipages.
You could even define ill-defined names like
#define BAD #*?$ some crap $?
And even more scary you can define things which are syntactically incomplete like
#define BADTASTE 2 +
and later code BADTASTE 3
Actually, you want to use parenthesis when defining macros. If you have
#define BADPROD(x,y) x*y
then BADPROD(2+3,4+5) is expanded to 2+3*4+5 which the compiler understands like 2+ (3*4) +5; you really want
#define BETTERPROD(x,y) ((x)*(y))
So that BETTERPROD(2+3,4+5) is expanded to ((2+3)*(4+5))
Avoid side-effects in macro arguments, e.g. BETTERPROD(j++,j--)
In general, use macros with care and have them stay simple.
Regarding these defines, it doesn't, the expanded macros doesn't have a type. The pre-processor which processes the #define is just replacing text within the source code
When you use these defines somewhere, e.g.
int i = INTEGER_EXAMPLE;
This will expand to
int i = 2;
Here the literal 2 (which in this context is an int) is assigned to an int.
You could also do:
char c = INTEGER_EXAMPLE;
Here too, the literal 2 is an int, and it is assigned to a char. 2 is within the limits of a char though, so all is ok.
You could even do:
int INTEGER_EXAMPLE = 2;
This would expand to
int 2 = 2;
Which isn't valid C.
#define STRING VALUE
is just an instruction for the pre-processor to replace the STRING with VALUE
afterwards the compiler will take control and will check the types
It doesn't, this is the preprocessor. The type of the constant is dependent on the context in which it is used. For instance:
#define INT_EXAMPLE 257
char foo = INT_EXAMPLE;
will attempt to assign 257 in a char context which should generate a warning unless char has more than 8 bits on your computer.
#Defines are nothing but literal replacements of values. You might want to use
static const
As it respects scope and is type-safe. Try this:
#define main no_main
int main() // gets replaced as no_main by preprocessor
{
return 0;
}
Should give you linking errors. Or you could try and fool your teacher by this
#define I_Have_No_Main_Function main //--> Put this in header file 1.h
#include"1.h"
int I_Have_No_Main_Function()
{
return 0;
}
It doesn't. The #define statements are processed before the compiler starts its work. Basically the pre-processor does a search and replace for what you wrote and replaces it, for instance, all instances of INTEGER_EXAMPLE are replaced with the string 2.
It is up to the compiler to decide the type of that 2 based on where it's used:
int x = INTEGER_EXAMPLE; // 2 is an integer
char y = INTEGER_EXAMPLE; // 2 is a char
Preprocessor cannot know the type of the macro definition. Preprocessor will just replace all occurrence of 'CHAR_EXAMPLE' with '2'. I would use cast:
#define CHAR_EXAMPLE ((char)2)
I define below data type:
typedef int MyInt;
Then I hope to define a new data type based on size of MyInt, something like below code, but I can't find a solution for it.
#if sizeof(MyInt) == 2
typedef long MyLong;
#else
typedef short MyLong;
#endif
Could anybody help?
It's not the preprocessor's job to evaluate sizeof, that's done by the compiler which is a later stage in the process. Evaluating sizeof needs deep C knowledge that the preprocessor simply doesn't have.
You could (in theory) consider the preprocessor as a separate step, that does text only transforms, in effect converting "foo.c" to "foo-preprocessed.c". The latter file won't have any #include or #ifs left, they're all evaluated and replaced by the preprocessor. The actual compiler never sees them.
You should consider using <stdint.h> and the known-precision types (uint16_t and friends).
You could use the values of macros such as UINT_MAX to determine the size of the underlying type.
You can use UINT_MAX - it can give you a clue about the size of integer.
#if (UINT_MAX <= 65536)
typedef long MyLong;
#else
typedef short MyLong;
#endif
New-enough GCC (I think 4.3) has predefined identifiers like __SIZEOF_LONG__, but it is simpler to just use the constants in limits.h as suggested by others.
Although I and the C preprocessor are sworn enemies, we sometimes need each other ;). So I would propose:
#if SIZEOF_MYINT == 2
# define MYLONG_T long
#elif SIZEOF_MYINT == 4
# define MYLONG_T short
#endif
typedef MYLONG_T MyLong;
Somewhere else (in a global config header file) you have your architecture dependent
#define SIZEOF_MYINT 2
For example, how can I get rid of "warning: unnamed struct/union that defines no instances" in the source file, not through compiler command-line options.
I want to define a C macro CONST_BUG_ON, which I use to check some const values at compile time.
#define CONST_BUG_ON(e) struct {int a:!(e);}
It gives the warning warning: unnamed struct/union that defines no instances, but in this case it is not a real problem.
Thanks Tom Tanner
#define CONST_BUG_ON_3(e, l) struct buggy##l {int a:!(e);}
#define CONST_BUG_ON_2(e, l) CONST_BUG_ON_3(e, l)
#define CONST_BUG_ON(e) CONST_BUG_ON_2(e, __LINE__)
That's good, but still have some problems: If file a's line 6 contain CONST_BUG_ON(e), and file a was inclued by file b, and line 6 of file b aslo contains CONST_BUG_ON(e), then gcc complains redefine error. Use__COUNTER__ instade of __LINE__ may perfect, but my old compiler does not support __COUNTER__.
Thanks Basile Starynkevitch
#define CONST_BUG_ON(e) do { \
int tab[__builtin_constant_p(e)?1:-1] = {0}; \
if (tab[0]) abort(); } while (0)
This is a C statement, can only be place in a function, I really want to use it outside the function.
One way to resolve the compiler’s complaint is that you have an unnamed struct that defines no instances is to give it a name:
#define CONST_BUG_ON(e) struct ForDebuggingOnly {int a:!(e);}
An alternate way to get the expression testing you want is to declare (but not define) an array that has an illegal size if e is true:
#define CONST_BUG_ON(e) extern int ForDebuggingOnly[(e) ? -1 : 1]
You could use macro magic to give yourself a unique ID by passing in the line number
#define CONST_BUG_ON_3(e, l) struct buggy##l {int a:!(e);}
#define CONST_BUG_ON_2(e, l) CONST_BUG_ON_3(e, l)
#define CONST_BUG_ON(e) CONST_BUG_ON_2(e, __LINE__)
That's fairly icky but it does give a unique name each time it is used (the 2nd level of indirection may be spurious, but this is what I have in some code that has stood the test of time).
It looks like what you try is called a compile time assertion or compile time assert macro. There are various ways to do this, usually involving arrays with negative dimension when the assertion fails. Many projects call this macro CT_ASSERT() and there are a bunch of Stackoverflow questions relating to them.
Assuming a recent GCC compiler, you could use __builtin_constant_p to test for compile-time constants, perhaps with
#define CONST_BUG_ON(e) do { \
int tab[__builtin_constant_p(e)?1:-1] = {0}; \
if (tab[0]) abort(); } while (0)
For your question about ignoring some warning, perhaps the GCC diagnostic pragmas could help.
If you want your CONST_BUG_ON to work only in declaration contexts, you might try
#define CONST_BUG_ON(e) CONST_BUG_AT(e,__LINE__)
#define CONST_BUG_AT(e,l) \
extern int tab_##l[__builtin_constant_p(e)?0:-1];
At last you could even customize your GCC compiler (with your specific pragma) perhaps using MELT (a high-level domain specific language to extend GCC), but that will take you days of work.
I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:
Names may be undefined with #undef,
usually to ensure that a routine is
really a function, not a macro:
#undef getchar
int getchar(void) { ... }
Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?
What it does
If you read Plauger's The Standard C Library (1992), you will see that the <stdio.h> header is allowed to provide getchar() and getc() as function-like macros (with special permission for getc() to evaluate its file pointer argument more than once!). However, even if it provides macros, the implementation is also obliged to provid actual functions that do the same job, primarily so that you can access a function pointer called getchar() or getc() and pass that to other functions.
That is, by doing:
#include <stdio.h>
#undef getchar
extern int some_function(int (*)(void));
int core_function(void)
{
int c = some_function(getchar);
return(c);
}
As written, the core_function() is pretty meaningless, but it illustrates the point. You can do the same thing with the isxxxx() macros in <ctype.h> too, for example.
Normally, you don't want to do that - you don't normally want to remove the macro definition. But, when you need the real function, you can get hold of it. People who provide libraries can emulate the functionality of the standard C library to good effect.
Seldom needed
Also note that one of the reasons you seldom need to use the explicit #undef is because you can invoke the function instead of the macro by writing:
int c = (getchar)();
Because the token after getchar is not an (, it is not an invocation of the function-like macro, so it must be a reference to the function. Similarly, the first example above, would compile and run correctly even without the #undef.
If you implement your own function with a macro override, you can use this to good effect, though it might be slightly confusing unless explained.
/* function.h */
…
extern int function(int c);
extern int other_function(int c, FILE *fp);
#define function(c) other_function(c, stdout);
…
/* function.c */
…
/* Provide function despite macro override */
int (function)(int c)
{
return function(c, stdout);
}
The function definition line doesn't invoke the macro because the token after function is not (. The return line does invoke the macro.
Macros are often used to generate bulk of code. It's often a pretty localized usage and it's safe to #undef any helper macros at the end of the particular header in order to avoid name clashes so only the actual generated code gets imported elsewhere and the macros used to generate the code don't.
/Edit: As an example, I've used this to generate structs for me. The following is an excerpt from an actual project:
#define MYLIB_MAKE_PC_PROVIDER(name) \
struct PcApi##name { \
many members …
};
MYLIB_MAKE_PC_PROVIDER(SA)
MYLIB_MAKE_PC_PROVIDER(SSA)
MYLIB_MAKE_PC_PROVIDER(AF)
#undef MYLIB_MAKE_PC_PROVIDER
Because preprocessor #defines are all in one global namespace, it's easy for namespace conflicts to result, especially when using third-party libraries. For example, if you wanted to create a function named OpenFile, it might not compile correctly, because the header file <windows.h> defines the token OpenFile to map to either OpenFileA or OpenFileW (depending on if UNICODE is defined or not). The correct solution is to #undef OpenFile before defining your function.
Although I think Jonathan Leffler gave you the right answer. Here is a very rare case, where I use an #undef. Normally a macro should be reusable inside many functions; that's why you define it at the top of a file or in a header file. But sometimes you have some repetitive code inside a function that can be shortened with a macro.
int foo(int x, int y)
{
#define OUT_OF_RANGE(v, vlower, vupper) \
if (v < vlower) {v = vlower; goto EXIT;} \
else if (v > vupper) {v = vupper; goto EXIT;}
/* do some calcs */
x += (x + y)/2;
OUT_OF_RANGE(x, 0, 100);
y += (x - y)/2;
OUT_OF_RANGE(y, -10, 50);
/* do some more calcs and range checks*/
...
EXIT:
/* undefine OUT_OF_RANGE, because we don't need it anymore */
#undef OUT_OF_RANGE
...
return x;
}
To show the reader that this macro is only useful inside of the function, it is undefined at the end. I don't want to encourage anyone to use such hackish macros. But if you have to, #undef them at the end.
I only use it when a macro in an #included file is interfering with one of my functions (e.g., it has the same name). Then I #undef the macro so I can use my own function.
Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.)
A little of both. Good code will not require use of #undef, but there's lots of bad code out there you have to work with. #undef can prove invaluable when somebody pulls a trick like #define bool int.
In addition to fixing problems with macros polluting the global namespace, another use of #undef is the situation where a macro might be required to have a different behavior in different places. This is not a realy common scenario, but a couple that come to mind are:
the assert macro can have it's definition changed in the middle of a compilation unit for the case where you might want to perform debugging on some portion of your code but not others. In addition to assert itself needing to be #undef'ed to do this, the NDEBUG macro needs to be redefined to reconfigure the desired behavior of assert
I've seen a technique used to ensure that globals are defined exactly once by using a macro to declare the variables as extern, but the macro would be redefined to nothing for the single case where the header/declarations are used to define the variables.
Something like (I'm not saying this is necessarily a good technique, just one I've seen in the wild):
/* globals.h */
/* ------------------------------------------------------ */
#undef GLOBAL
#ifdef DEFINE_GLOBALS
#define GLOBAL
#else
#define GLOBAL extern
#endif
GLOBAL int g_x;
GLOBAL char* g_name;
/* ------------------------------------------------------ */
/* globals.c */
/* ------------------------------------------------------ */
#include "some_master_header_that_happens_to_include_globals.h"
/* define the globals here (and only here) using globals.h */
#define DEFINE_GLOBALS
#include "globals.h"
/* ------------------------------------------------------ */
If a macro can be def'ed, there must be a facility to undef.
a memory tracker I use defines its own new/delete macros to track file/line information. this macro breaks the SC++L.
#pragma push_macro( "new" )
#undef new
#include <vector>
#pragma pop_macro( "new" )
Regarding your more specific question: namespaces are often emul;ated in C by prefixing library functions with an identifier.
Blindly undefing macros is going to add confusion, reduce maintainability, and may break things that rely on the original behavior. If you were forced, at least use push/pop to preserve the original behavior everywhere else.