+ 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; }

16th May 2022, 6:16 AM
blueshipswims
blueshipswims - avatar
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.👍
16th May 2022, 7:04 AM
arturop200
arturop200 - avatar
+ 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
16th May 2022, 6:35 AM
Raul Ramirez
Raul Ramirez - avatar
0
Arturop gottcha...makes sense
19th May 2022, 12:32 PM
blueshipswims
blueshipswims - avatar
- 2
Hiii
18th May 2022, 5:46 AM
Suhas Kaneriya