+ 1
why does case 2 yields error(error: 'ch' undeclared (first use in this function)). when its perfectly okey to declare 'i' inside
why does case 2 yields error(error: 'ch' undeclared (first use in this function)). when its perfectly okey to declare 'i' inside the loop (used in both) so why can't we declare 'ch' inside loop???? CASE 1 : char ch; for (int i = 0; ch != '\n'; i++) { scanf("%c", &ch); name[i] = ch; } CASE 2 : for (int i = 0; char ch != '\n'; i++) { scanf("%c", &ch); name[i] = ch; }
4 Answers
0
in the expression: char ch != '\n'
its not correct, at first it seems like it is stating a declaration/initialization of the variable ch but suddenly it changes to a comparison != (not equal to).
I believe it is a nice and interesting syntax error.š
+ 1
A for loop is basicaly :
declaration;
while(condition) {
//do this
//update
}
short hand:
for(declaration;condition;update){
// Do this
}
So you need to decalare ch in the declaration part in order to work in all parts
So if you had decalred int i in the condition it also wouldnt work
0
Arturop gottcha...makes sense
- 2
Hiii