Reading variables with C preprocessor - c

I'm running into the following problem when trying to use concatenation with the C preprocessor:
#define substitute(id) var##id
int main()
{
int var0 = 999;
int var1 = 998;
int var2 = 997;
int var3 = 996;
int var4 = 995;
int i = 0;
for(i; i < 5; i++)
{
printf("Valor: %i \n", substitute(i));
}
system("PAUSE");
return 0;
}
Is there a way for the preprocessor to be able to read the value on "i" instead of just concatenating "vari"?

No. The preprocessor works before compilation and therefore before execution.
The define
#define substitute(id) var##id
will cause your loop to expand to:
for(i; i < 5; i++)
{
printf("Valor: %i \n", vari);
}
The preprocessor has no knowledge of the variable i, nor should it.
You should probably use an array:
int var[5] = {999,998,997,996,995};
and access it via []:
for(i; i < 5; i++)
{
printf("Valor: %i \n", var[i]);
}

That's not possible at the pre-processor stage because what you want depends on values that are only known later, at runtime.
What you need is an array and the index operator, var[i].

You need to be aware that the macro is resolved once (by the preprocessor) before the file is compiled, so at runtime, each iteration in the loop will render the same result when "calling" substitute.

Nope, because the preprocessor runs at compile time, not runtime, but you can use an array:
int vars[] = { 999, 998, 997, 996, 995 };
for (int i = 0; i < 5; ++i)
printf("Valor: %i \n", vars[i]);

No i is a runtime evaluation. There is no way for the preprocessor to know what the value of I could be.

Why would you do this with the preprocessor?
You seem to be trying to reinvent arrays:
int main() {
int var[] = {999, 998, 997, 996, 995};
int i;
for (i=0; i<5; i++)
printf("Valor: %i\n", var[i]);
return 0;
}

As many said - no, macros doesn't know anything about what's going on in program compile-time or run-time. But... if you wish you can generate some hackish code with macro which operates with stack directly (do not try this in home alone - it can blow your computer apart !! :-) )- define your macro as:
#define substitute(adr, max, id) *(adr + max - id)
and call like this:
printf("Valor: %i \n", substitute(&var4,4,i));
But keep in mind that this is just for curiosity, in real life it is not recommended to play directly with stack, because compiler may (and usually will) re-order variable allocation on stack and also you will risk some nasty bugs to happen and etc... So better as others said - make some array and operate on that.
hth!

C macros are only expanded at compile time and your printf line would become
printf("Valor: %i \n", vari);

Related

Variable address varies weather we diplay it or not?

Can anyone explain this?
Consider this program. We write modify dest[10] intentionally in order to see j value modified.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char source[] = "Hello";
int j = 100;
char dest[10];
dest[12] = 'A';
printf("j = %d \n", j);
fflush(stdout);
printf("j = %d \n", j);
fflush(stdout);
printf("*j = %p \n", &j); // comment this line to get another result!
return 0;
}
output :
j = 4259940
j = 4259940
*j = 0x7ffcc4cdef74
But if we comment the line displaying j varibale address printf("*j = %p \n", &j); we get:
j = 100
j = 100
It is like j is stored elsewhere, not just after dest variable as in the first example.
Any explanation?
Where and whether to store the objects j and dest and how to handle the out-of-bounds access in dest[10] is the compiler’s choice. Modern compilers do many complicated things to optimize programs. When you omit the statement that prints the address of j, the compiler makes different choices, and these produce different results.
A variable is not required to have any storage address if the address is not taken.
The compiler is free to only hold the value in a register or completely remove it via optimization mechanisms and only use the constant value 100 directly.
You might check if you corrupted dest instead when j is not stored on the stack.

While-loop not breaking when extra 'int' keyword added?

I was doing some exercises on codewars, and had to make a digital_root function (recursively add all digits of a number together, up untill there's only one digit left).
I was fairly confident that I did it right, but for some reason my while-loop never broke, even though my prints showed that len was 1.
#include <stdio.h>
#include <string.h>
int digital_root(int n) {
char number[10];
sprintf(number, "%d", n);
int len = strlen(number);
printf("Outer print: %s %d %d\n", number, n, len);
int sum = 0;
while(len > 1)
{
sum = 0;
for(int i = 0; i<len; i++)
{
sum += number[i] - '0';
}
sprintf(number, "%d", sum);
int len = strlen(getal); //!!!
printf("Inner print: %s %d %d\n", number, sum, len);
}
return sum;
}
It took me a long time to figure out what was wrong. I noticed that I copy pasted the 'int' keyword when I recalculated the len in the while loop (line marked with !!!). When I removed that (because it was not needed to redefine it as an int, it already was), everything suddenly worked like it was supposed to.
This kinda confused me. Why would this matter? I understand that redefining it is bad practice, but I don't get how this would result in the while-loop not breaking?
The used compiler is Clan3.6/C11.
(Ps. When I tried the same code in TIO, it worked in both cases...)
You're not redefining an existing variable, you're defining a new variable.
Consider this example:
#include <stdio.h>
int main(void) {
int x = 42;
printf("Outside, start. x (%p) = %d\n", (void *)&x, x);
{
printf("Inner block, start. x (%p) = %d\n", (void *)&x, x);
int x = 123;
printf("Inner block, end. x (%p) = %d\n", (void *)&x, x);
}
printf("Outside, end. x (%p) = %d\n", (void *)&x, x);
return 0;
}
Sample output:
Outside, start. x (0x7ffd6e6b8abc) = 42
Inner block, start. x (0x7ffd6e6b8abc) = 42
Inner block, end. x (0x7ffd6e6b8ab8) = 123
Outside, end. x (0x7ffd6e6b8abc) = 42
[Live demo]
This program outputs the memory address and value of x. Most uses of x refer to the outer variable declared at the beginning of main. But within the inner block, after int x = 123;, all occurrences of x refer to a second, separate variable that happens to also be called x (but is otherwise independent).
When execution leaves the inner block, the outer x variable becomes visible again.
This is also referred to as shadowing.
In your code, the outer len is never modified, so while(len > 1) is always true.
By the way, shadowing is a very common concept in most languages that support block scoping:
Perl
JavaScript
Haskell
Common Lisp
Your second int len creates a second, parallel, variable that goes away at the end of the {} block. The original len then returns to life, completely unchanged. Without the second int the original variable is changed. With it the original len is effectively an unchanged constant and infinite loop.

C's For loop's arguments

I want to initialize an 16-cel-long array with 0, 1, 2 and 3 by blocks of four cels. So here is my first attempt at this:
int main(void) {
int t[16];
int i;
for (i = 0; i<=15; t[i++]=i/4)
{
printf("%d \n", t[i]);
}
return 0;
}
However, here is what I get. I know I can do it differently by just getting the affectation into the for loop, but why does this not work?
EDIT: Please do note that the printf only serves to check what the loop did put in the array.
The initialization works fine; you're just printing the cell before initializing it. Remember that the loop increment is done after each iteration. If you unroll the loop, you have:
i = 0; /* i is now 0 */
print(t[i]); /* prints t[0] */
t[i++] = i/4; /* sets t[0] */
/* i is now 1 */
print(t[i]); /* prints t[1] */
t[i++] = i/4; /* sets t[1] */
/* i is now 2 */
print(t[i]); /* prints t[1] */
/* etc. */
As well as the off-by-one errors with the loop begin/end that have been mentioned in other posts, this code:
t[i++]=i/4
causes undefined behaviour because i is read and written without a sequence point. "Undefined behaviour" means anything can happen: the value could be 3, or 4, or anything else, or the program could crash, etc.
See this thread for more in-depth discussion, and welcome to C..:)
I do not understand what you are trying to accomplish, but please let me show you a similar piece of code, first.
int main(void) {
int t[16];
int i;
//edited the code; providing standard way to do the task
for (i = 0; i<=15; i++)
{
t[i]=i/4;
printf("%d \n", t[i]);
}
return 0;
}
EDIT:
The while loop should be written that way:
int i = 0;
while (i<=15){
t[i] = i%4;
i++;
}
Which means set t[i] equal to i%4 and then increment i.
Since you are a beginner, I've updated the for loop and it now provides a standard way to do your task. It's better to have a simple increment on the third for loop command; do the rest of the job inside the for loop, as described above.
#naltipar: Yeah, I just forgot to initialize the first cel, just like grawity pointed out. Actually, the version I wrote for myself was with i++ but even then, since the third expression is executed after each loop, it sent out the same result. But whatever, it is fixed now.
However, I've got another problem which I'm sure I'm missing on but still can't figure it out:
int i = 0;
while (i<=15)
t[++i] = i%4;
This was first:
for(i = 0; i<=15; t[++i] = i%4);
but it resulted with an infinite loop. So in order to make sure that's not a problem specific to for, I switched to while andthe same thing still happens. That being said, it doesn't occur if i replace ++i by i++. I unrolled the whole loop and everything seems just fine...
I'm a beginner, by the way, in case you were wondering.
A clearer way to write this would be much less error-prone:
for (i = 0; i < 16; ++i)
printf ("%d\n", (t[i] = i % 4));
Personally I'd code something that way, but I'd never recommend it. Moreover, I don't really see much benefit in condensing statements like that, especially in the most important category: execution time. It is perhaps more difficult to optimize, so performance could actually degrade when compared to simply using:
for (i = 0; i < 16; ++i)
{
t[i] = i % 4;
printf ("%d\n", t[i]);
}
Even if it is you reading your own code, you make it difficult for your future self to understand. KISS (Keep It Simple, Stupid), and you'll find code is easier to write now and just as easy to modify later if you need to.

How to make a variable value passage for preprocessor?

Here I know that the following code simply copies the character i rather than its value to the preprocessor statement (which makes a error for undefined symbol i in compile-time).
What I want is:
Is their a way such that the compiler treats, i as a variable with some value rather than a character ?
#include <stdio.h>
#define PRINT(x) printf("%d \n", y ## x)
int main(void) {
int y1=0 , y2=1 , y3=4;
for(int i=1; i <= 3; ++i) {
PRINT(i);
}
return 1;
}
About the pre-processor
First of all, I think there's a need to clarify how the preprocessor works: it pre-processes the input files, which means it runs before the compiler. Unfortunatly, for historical reasons, it doesn't know anything about C or C++, doesn't parse anything, and just does very simple textual operations on words and parenthesis. Just to illustrate my point:
#define this __FILE__
#define file -- Hell no!
#define fine(a, b) fine: a ## _ ## b
Ok, so this is not a valid C or C++ file
But the preprocessor will run just fine(go, try!)
Run this with a pre-processor, for example gcc -x c -E -P test.txt and you'll get:
Ok, so "test.txt" is not a valid C or C++ -- Hell no!
But the preprocessor will run just fine: go_try!
So, obviously, when the preprocessor sees PRINT(i) in your code, it replaces it with printf("%d \n", yi) without thinking much about it. And it has absolutely no idea i is a variable, don't even think about evaluating it's value.
Solutions
Basically, what you want is print a bunch of numbers.
You could simply do
printf("0\n1\n4\n");
But this lacks makes changing numbers cumbersome,
so let's go with
printf("%d\n%d\n%d\n", 0, 1, 4);
Which makes it easy to change a number, but not to add/remove one.
Ok so how about:
printf("%d\n", 0);
printf("%d\n", 1);
printf("%d\n", 4);
Yeah, you can change/add/remove numbers easily but as any sane programmer you hate repetition. So, we need some kind of loop.
By far the simplest and most straightforward way to iterate in C is at runtime, using an array:
int [] y = { 0, 1, 4 };
for(int i = 0; i < sizeof(y)/sizeof(int); ++i) {
printf("%d\n", y[i]);
}
If you want, you can hide the printf using a function:
inline void print_int(int* y, int i) { print_int(y[i]); }
int [] y = { 0, 1, 4 };
for(int i = 0; i < sizeof(y)/4; ++i) print_int(y, i);
And going further with functions:
inline void print_int(int x) { printf("%d\n", x); }
inline void print_int(int* y, int i) { print_int(y[i]); }
inline void print_ints(int * y, int n)
{
for(int i = 0; i < n; ++i)
print_int(y, i);
}
template<int n> // C++
inline void print_ints(const int[n] & y) { print_ints(&y[0], n); }
int [] y = { 0, 1, 4 };
print_ints(y); // C++
// or in C:
print_ints(y, sizeof(y)/sizeof(int));
Now, what if you absolutely want the generated code to look like solution 3. ? This means you need the iteration to happen at compile-time. Tricky!
That's where the preprocessor can come into play. There are (hacky) ways to make it do this kind of things. I strongly recommend not implementing this yourself (except to play), but use the Boost.preprocessor library instead:
#define PRINTER(R,D, NUMBER) printf("%d\n", NUMBER);
#define NUMBERS (0, 1, 4)
BOOST_PP_LIST_FOR_EACH(PRINTER, _, BOOST_PP_TUPLE_TO_LIST(NUMBERS))
// will expand to printf("%d\n", 0); printf("%d\n", 1); printf("%d\n", 4);
Under standard C, this is not possible; during preprocessing, the compiler simply sees the identifier i as simply that - an identifier. It does not know that i is of type int, or that it's even a variable in the first place.
The easiest way to achieve what's intended is to use an array, like so:
int i;
int y[] = { 0, 1, 4 };
for (i = 0; i < 3; i++) // NOTE: arrays in C start at index 0, not 1
{
printf("%d \n", y[i]);
}
Also note that I got rid of the macro, as you want to use the value of a runtime variable i to select another runtime variable.

C - not entering if even when he should

I'm seriously mad right now. I need to compare one string with second, when chars from second string can somehow create first string. Example
foo1 = bill
foo2 = boril
foo2 can create foo1, because it contains all the letters from foo1.
So there's my program:
secret = religion
lettersGuessed = religonvpst
for(i = 0; i < lenSecret; i++){
for(l = 0; l < lenGuessed; l++)
printf("A: %c, B: %c, C: %d\n", secret[i], lettersGuessed[l], count);
if(secret[i] == lettersGuessed[l]){
printf("HI\n");
count++;
break;
}
printf("C: %d\n", count);
}
But variable count always stays at 0. This is output from console:
http://pastebin.com/YrHiNLNi
As you can see right from beginning, when secret[i] == lettersGuessed[l] in if should return true(1), it returns false(0). What's wrong with this? Why it's not working?
It's because you don't have curly braces after your second for loop. If you don't wrap the block of code you want to iterate over with curly braces, only the code before the first semi-colon encountered will be executed. In this case, your second loop will iterate over the printf statement but nothing else. So variable l will always be equal to lenGuessed when the if statement is executed and no letter from the first word matches the last letter of the second word, therefore count is never incremented.
Ok, this is totaly crazy.
Code that I posted in my question was of course wrong, because I forget braces of second for loop. Small, but fatal mistake, I know, but I was seriously mad so I didn't pay attention. Anyway, the original code is following:
int isWordGuessed(char secret[], char lettersGuessed[]){
int i, l, count = 0;
int lenSecret = strlen(secret);
int lenGuessed = strlen(lettersGuessed);
for(i = 0; i < lenSecret; i++)
for(l = 0; l < lenGuessed; l++)
if(secret[i] == lettersGuessed[l]){
count++;
break;
}
return lenSecret == count ? 1 : 0;
}
At first, it was returning 0. After compiling it with different tools and launching it on two different OS (Windows 7 64-bit and Windows XP 32-bit) i was finaly able to get 1 from that function.
It seems like variable count had non-zero value while launching, so instead of int i, l, count; I wrote int i, l, count = 0;
Well, now I don't understand only one thing - why sometimes variables has non-zero value even when I never touched them. It happened to my before, but only in C, in other languages I never had such a problem.

Resources