I am getting a 'bad suffix on number' and a missing parenthesis at the last printf.
Do you have any idea why this is not working?
#include <stdio.h>
#define suma(a, b) a + b
#define alipire(a,b) a##b
int main()
{
int a = 2, b = 3, maxim;
maxim = a > b ? a : b;
printf("%d \n",suma(a, b)*5);
printf("%d", alipire(suma(a, b), maxim));
return 0;
}
When the macro suma(a, b) is replaced in printf("%d \n",suma(a, b)*5);, the result is printf("%d \n",a + b *5);, which may not be what you want as it multiplies b by 5 before adding a.
When alipire(suma(a, b), maxim) is replaced, the steps are:
alipire is initially replaced by suma ( a , b ) ## maximum. I inserted spaces to emphasize the organization into preprocessor tokens.
The ## is processed to concatenate tokens. This would form suma ( a, b )maximum. However, )maximum is not a valid preprocessor token. Per the rule in C 2018 6.10.3.3 3, the behavior is not defined.
Attempting to reproduce the problem with various major compilers, include MSVC, on Compiler Explorer yielded various error messages but not “bad suffix on number”. Perhaps you are using an older version of Visual Studio or the source code that produced that error was different from the source code shown in the question. So specific analysis for that error message cannot be done without more information, such as the specific compiler version and command-line switches used.
Related
I am running the following program and getting a result as 9 7, I understood why 9 is the output but I can't figure out why I'm getting 7 as output.
#include<stdio.h>
#define sqr(i) (i*i)
int main()
{
printf("%d %d", sqr(3), sqr(3+1));
return 0;
}
For the second function that is sqrt(3+1) how the micro is getting expanded and how Im getting 7 output?
You can have the compiler or IDE preprocess the file and show you how the macro expanded.
In your case sqr(3+1) expands to (3+1*3+1). Now the precedence of C operators means that the multiplication is done before the addition. So (3+1*3+1) -> (3+3+1) -> (7).
You can fix this by defining your macro this way, with parentheses around the argument:
#define sqr(i) ((i)*(i))
I want to know how the C preprocessor handles circular dependencies (of #defines). This is my program:
#define ONE TWO
#define TWO THREE
#define THREE ONE
int main()
{
int ONE, TWO, THREE;
ONE = 1;
TWO = 2;
THREE = 3;
printf ("ONE, TWO, THREE = %d, %d, %d \n",ONE, TWO, THREE);
}
Here is the preprocessor output. I'm unable to figure out why the output is as such. I would like to know the various steps a preprocessor takes in this case to give the following output.
# 1 "check_macro.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "check_macro.c"
int main()
{
int ONE, TWO, THREE;
ONE = 1;
TWO = 2;
THREE = 3;
printf ("ONE, TWO, THREE = %d, %d, %d \n",ONE, TWO, THREE);
}
I'm running this program on linux 3.2.0-49-generic-pae and compiling in gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5).
While a preprocessor macro is being expanded, that macro's name is not expanded. So all three of your symbols are defined as themselves:
ONE -> TWO -> THREE -> ONE (not expanded because expansion of ONE is in progress)
TWO -> THREE -> ONE -> TWO ( " TWO " )
THREE -> ONE -> TWO -> THREE ( " THREE " )
This behaviour is set by §6.10.3.4 of the C standard (section number from the C11 draft, although as far as I know, the wording and numbering of the section is unchanged since C89). When a macro name is encountered, it is replaced with its definition (and # and ## preprocessor operators are dealt with, as well as parameters to function-like macros). Then the result is rescanned for more macros (in the context of the rest of the file):
2/ If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced…
The clause goes on to say that any token which is not replaced because of a recursive call is effectively "frozen": it will never be replaced:
… These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.
The situation which the last sentence refers rarely comes up in practice, but here is the simplest case I could think of:
#define two one,two
#define a(x) b(x)
#define b(x,y) x,y
a(two)
The result is one, two. two is expanded to one,two during the replacement of a, and the expanded two is marked as completely expanded. Subsequently, b(one,two) is expanded. This is no longer in the context of the replacement of two, but the two which is the second argument of b has been frozen, so it is not expanded again.
Your question is answered by publication ISO/IEC 9899:TC2 section 6.10.3.4 "Rescanning and further replacement", paragraph 2, which I quote here for your convenience; in the future, please consider reading the specificaftion when you have a question about the specification.
If the name of the macro being replaced is found during this scan of the replacement list
(not including the rest of the source file’s preprocessing tokens), it is not replaced.
Furthermore, if any nested replacements encounter the name of the macro being replaced,
it is not replaced. These nonreplaced macro name preprocessing tokens are no longer
available for further replacement even if they are later (re)examined in contexts in which
that macro name preprocessing token would otherwise have been replaced.
https://gcc.gnu.org/onlinedocs/cpp/Self-Referential-Macros.html#Self-Referential-Macros answers the question about self referential macros.
The crux of the answer is that when the pre-processor finds self referential macros, it doesn't expand them at all.
I suspect, the same logic is used to prevent expansion of circularly defined macros. Otherwise, the preprocessor will be in an infinite expansion.
In your example you do the macro processing before defining
variables of the same name, so regardless of what the result
of the macro processing is, you always print 1, 2, 3!
Here is an example where the variables are defined first:
#include <stdio.h>
int main()
{
int A = 1, B = 2, C = 3;
#define A B
#define B C
//#define C A
printf("%d\n", A);
printf("%d\n", B);
printf("%d\n", C);
}
This prints 3 3 3. Somewhat insidiously, un-commenting #define C A changes the behaviour of the line printf("%d\n", B);
Here's a nice demonstration of the behavior described in rici's and Eric Lippert's answers, i.e. that a macro name is not re-expanded if it is encountered again while already expanding the same macro.
Content of test.c:
#define ONE 1, TWO
#define TWO 2, THREE
#define THREE 3, ONE
int foo[] = {
ONE,
TWO,
THREE
};
Output of gcc -E test.c (excluding initial # 1 ... lines):
int foo[] = {
1, 2, 3, ONE,
2, 3, 1, TWO,
3, 1, 2, THREE
};
(I would post this as a comment, but including substantial code blocks in comments is kind of awkward, so I'm making this a Community Wiki answer instead. If you feel it would be better included as part of an existing answer, feel free to copy it and ask me to delete this CW version.)
What will the program print when the inputs are 2,3?
#include <stdio.h>
#define min(a,b) ((a) > (b) ? (b) : (a))
#define inc(a) a++
#define mult(a,b) (a * b)
int main(void) {
int x = 1, y = 2;
scanf("%d %d",&x,&y);
printf("min(%d,inc(%d))",x,y);
printf("=%d\n",min(x,inc(y)));
printf("min(mult(%d,%d+2),11)",x,y);
printf("=%d\n",min(mult(x,y+2),11));
return 0;
}
edit: I get funny answer for negative numbers i.e -1,-2.
Why is inc(-2) change y to zero instead of -1?
Think of a macro as simply string replacement. Just replace the macro name and parentheses with the body of the macro definition, replacing the macro parameters with what is passed in. An example is easier:
#define hello(a) a+a
...
int y = hello(x);
Would be replaced with:
int y = x+x;
To answer your question, do this manually, and very, very carefully. For nested macros, start with the inside one. Did I mention do this carefully? Don't add or remove any sets of parentheses.
The output would be:
min(2,inc(3))=2
min(mult(2,4+2),11)=11
What do you mean with overwrite?
If you define a function like you did above and call for example this:
inc(x);
.. then the compiler turns it into x++. The variable a is just a name for the "paramter" and will also be replaced by the real variable.
What operating system are you running? you can easily run this yourself and see the results
if your on Windows I would suggest getting CodeBlocks or Visual Studios
if your on Linux or MAC , learn to compile from terminal using gcc or g++
I am having a code which requires to concatenate strings as shown below:
#define CMD(A,B) CMD_##A_PROMPT##B
void main()
{
int a = 10, b = 5;
printf("%s\n", CMD(a, b));
}
the desired output is: CMD10_PROMPT5
Can this be achieved by any means?
I don't think that this can be done, because the macro you're looking for is a compile-time "stringification", an the parameters receive their values at run-time.
If you're looking for run-time "stringification", use sprintf and the like.
You can do it by replacing int a = 10, b = 5; with:
#define a 10
#define b 5
Otherwise it's not possible. C translation occurs in a series of phases defined in the standard, and preprocessing phase occurs before any object definitions are parsed. As far as the preprocessor is concerned, int a = 10 does not establish any relationship between the token a and the token 10.
If all you're after is the output, do it like this:
#define CMD_PATTERN "CMD_%d_PROMPT%d"
int main() {
int a = 10, b = 5;
printf(CMD_PATTERN "\n", a, b);
}
There's unfortunate requirement that the arguments are supplied in the same order that they appear in the pattern - this makes it difficult to change the order in future. For that reason, it might be better to define a formatting function rather than just a pattern.
I have code like
#define ONE 1
#define TWO 2
#define SUM (ONE+TWO)
How do I dump SUM as "3", the resolved value, in gcc 4.3+?
gcc -dM -E foo.h only seems to dump it as is. How do I get the actual value like it's inserted on compilation stage?
You can't. As far as the compiler is concerned, the line printf("%d\n", SUM) before preprocessing is indistinguishable from the line printf("%d\n", 1+2). The compiler just happens to perform an optimization called constant folding, even at the default optimization level (-O0), which turns the result into a constant 3 at runtime.
There's not really a good way to see the output of these optimizations. You could use the -S option to view the generated assembly code and see what that looks like, but if your program is anything larger than a toy, that will be a lot of manual effort. You could also look at the parse tree by using one of the -fdump-tree options (see the GCC man page).
You can't "dump" SUM as 3 because SUM isn't 3 in any meaningful sense, it's just a sequence of the three tokens ONE, + and TWO. What it turns into depends on the context where it is expanded.
Macros are expanded where they appear in the source, macro replacements are just strings of tokens until then.
You can test this like this.
#include <stdio.h>
#define ONE 1
#define TWO 2
#define SUM ONE+TWO
int a = SUM;
#undef ONE
#define ONE 2
int b = SUM;
int main()
{
printf("a = %d\nb = %d\n", a, b);
return 0;
}
Here's another example:
#include <stdio.h>
#define ONE 1
#define TWO 2
#define SUM ONE+TWO
int main()
{
/* prints 6, not 2 */
printf("5 - SUM = %d\n", 5 - SUM);
return 0;
}
With this example there's no way you can justify SUM being 3.
Contrary to the other answers, there's definitely a solution to this problem, especially with gcc extensions. Parse the output of gcc -dM and generate a C file containing lines of the form __typeof__(MACRO) foo = MACRO; and go from there. Without __typeof__ you could still handle all arithmetic types fairly well by just using long double.
One way is to stop at the precompiler stage (-E) and examine that output.