Is it safe to use assignment in state? C / C ++, C #

we had a programming lesson today. A very simple exercise in the console. I wrote a loop to load from char to char using getchar () with the purpose, all in terms of a loop.

char c; while((c = getchar()) != '\n'){ ... 

Someone says that it is unsafe, others say that in C / C ++ I can do this, but not in C #.

I tried this

 string s; if((s = Console.ReadLine()) != ""){ ... 

But this also works, so I don’t understand why it is unsafe. Or isn’t it?

Edit: \ I also read this. Why are you using assignment in state? but this is not the answer to my question at all.

+4
source share
2 answers

The main operation in your example != , Which is not the destination. What you cannot do in C # (and I think it was the right design decision) looks something like this:

 if (s = "") ... 

The problem here is that it is very similar to the usual equal operator == . There are times when this code is intentional, but it is usually a typo that is very difficult to find. Compare this to this:

 if (s == "") ... 

When you are looking for an error in your code, you can easily overlook this.

+2
source

You can argue about the readability of such code (and it will not pass the code review in most places where I worked), but the problem is not what the task is. The problem is that getchar() does not return a char , it returns int . And that set of possible return values ​​will not match the char value. If you change your code in:

 int c; while ( (c = getchar()) != EOF && c != '\n' ) { ... 

it will be "safe" (but I still don’t want to support it). if you want to update c in the path control use the for loop:

 for ( int c = getchar(); c != EOF && c != '\n'; c = getchar() ) { ... 

It is at least readable.

+3
source

Source: https://habr.com/ru/post/1441798/


All Articles