This code is intended to call the s () function every time I press the s key. But instead, the s () function is constantly called:

#include <stdio.h> void s() { printf("What?"); } int main(void) { char control; while(1) { control = getch(); if(control = 's') { s(); } } } 

Closed due to the fact that off-topic participants Mike , insolor , Bald , Kromster , pavel Oct 5 '16 at 14:25 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - Mike, insolor, Bald, Kromster, pavel
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • four
    if(control == 's') you assign = instead of compare == wrote - Mike
  • Thank you very much. Just great. - Alex Smolyakov
  • Yeah, you still call it yourself) do not confuse assignment = and test for equality == - Malov Vladimir
  • Apparently I still confuse it. And in si this is fatal. - Alex Smolyakov
  • > caused by a problem that is no longer reproduced, or a typo. -> Yes, in principle, I definitely will not be offended if they demolish. He may not bear the benefit. - Alex Smolyakov

1 answer 1

The Yoda notation saves from such errors. Here it will compile. Maybe with abuse (depends on the compiler and its settings), but compiles:

 if( control = 's' ) 

But this is not compiled in principle:

 if( 's' = control ) 
  • With modern compilers, reverse notation is not needed, they issue a warning. - VladD
  • one
    not always. It is better to pass the compiler explicitly to -pedantic -Wall -Werror . How many bugs I did not let in the prod thanks to this. The Yoda notation is not needed - it is terrible. - KoVadim
  • @VladD, not so often you can find large source files that are silently compiled, at least with -Wall -pedantic . Therefore, many people just forget to watch the warnings: ( - PinkTux
  • and then “oh, we have bugs”, “we need to test more”, “we need static code analyzers” and the like. - KoVadim
  • @KoVadim, so this is already "later." I often collect some pribludy from the source - it gets out there so much ... Even as simple as 2 pennies cadaver and that gives a lot. But analyzers are still needed :) The same cppcheck not bad catches all sorts of little things about which the compiler is silent. - PinkTux