The debugger tells me I don't use my variable but also that it is not declared. What is going on here? is an if statement it's own scope? Somehow it seems to be the case that an array of fixed length is not in the same scope inside of an if block.
My Minimal example
#include <stdio.h>
#include <stdlib.h>
void nullarray(int start,int end, char array[]){
if(start<end) // TODO used to be <=
{
array[start]='0';
nullarray(++start,end,array);
}else{array[start]='\0';}
}
int main()
{
int commaindex2=-1;
int mostdecimaldigits=6;
if(commaindex2==-1){
char decimalnum2[1];decimalnum2[0]='0';
}
else{
char decimalnum2[mostdecimaldigits]; // get enought store incl filling up zeros
nullarray(0,mostdecimaldigits,decimalnum2); // write zeros to array
}
printf("%s", decimalnum2);
}
Debugger Output
||=== Build: Debug in test4 (compiler: GNU GCC Compiler) ===|
D:\main.c||In function 'main':|
D:\main.c|20|warning: variable 'decimalnum2' set but not used [-Wunused-but-set-variable]|
D:\main.c|27|error: 'decimalnum2' undeclared (first use in this function)|
D:\main.c|27|note: each undeclared identifier is reported only once for each function it appears in|
||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
however this works fine
int main()
{
int commaindex2=55;
int mostdecimaldigits=6;
int num;
if(commaindex2==-1){
num=1 ;
}
else{
num=mostdecimaldigits;
}
char decimalnum2[num];
nullarray(0,num,decimalnum2);
printf("%s", decimalnum2);
}
What is going on here? Is an if statement it's own scope?
Yes - the if
statement (or, to be precise, the curly braces following it) defines its own scope, as do the braces after the else
statement (but that's a different scope).
Thus, your declarations char decimalnum2[1];
and char decimalnum2[mostdecimaldigits];
(in the if
and else
blocks, respectively) define variables (separate, unrelated ones) that are valid only within the braces in which they occur.
So, the statement: printf("%s", decimalnum2);
, which is outside both blocks, is attempting to use an undeclared variable - hence the error.
Further, the statement decimalnum2[0]='0';
(in the if
block) assigns a value to the (block-local) variable that is then never used - hence the warning.
Quick Solution: You need to put the char decimalnum2[mostdecimaldigits];
declaration both before and outside the if … else
blocks, and remove the two declarations inside those blocks.