简体   繁体   中英

C++ indentifier “read” conflicts?

Recently I'm working on my toy final c++ project, which will read content from a file at the begining and then process it.

Here's the simplified code.

#include <iostream>
#include <fstream>
//using namespace std;
struct command{
    int a;
};
command read[1]; 
int main() {
    std::ifstream fin;
    fin.open("123.txt");
    if (!fin){
        std::cout << "failed" << std::endl;
        return 0;
    }
    char c;
    fin >> c;
    std::cout << c;
    return 0;
}

It works fine with Visual Studio 2019 . However, when I'm trying to use devc++ 5.11 TDM-GCC 4.9.2 , a strange bug happens. I get a segmentation fault on line fin>>c; , with return code 3221225477.

With great effort, the easiest way to make this code works is changing the identifier read to names like reading or whatever. Besides, moving the line command read[1]; into main function also helps.

My questions are:

  • Is it a behavior related to the compiler? MSVC is fine but GCC 4.9.2 is a little bit old or...?
  • Does the identifier read conflict with something in my code? Why does it not a compile error but a segmentation fault?
  • Why does moving the declaration of read into main function help?

Update:Thanks for tips and I removed using namespace std . I think it has something to do with ifstream , because just std::cout<<"hello world"; works. -Wall -Wextra provides no warnings.

GCC compiler is stricter than other compiler.

According to tadman's describe, we can guess there's read symbol in namespace std.

So you put it out of main,it's a conflict, you put in the main, it become a local symbol.

There is very likely a collision happening between your read and another in the global namespace. Not all compilers handle this situation the same way, but you can always avoid it if you are careful.

Visual Studio's Intellisense (or whatever alternative you prefer) can help you identify what symbol your read is colliding with. To do that, scope or comment out your code, then start typing " read ". If there's another read in your scope, you'll likely see it and be able to get information about it.

This is one of the reasons I don't like using namespace std; . It pollutes your global namespace with a bunch of stuff and increases your chance of collision with a standard library identifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM