简体   繁体   中英

Dev-C++ gives '&' reference syntax error

What's the matter with Dev-C++, or are there errors in my code about using reference variable?

#include <stdio.h>

    struct P {
        int x;  
    };

    int main(int argc, char **argv){
        struct P Point[5];
        struct P & rPoint;

        int i;
        for(i=0;i<=4;i++) {
            rPoint = Point[i]; // I know. I can use Point[i].x = i. But...
            rPoint.x = i;
        }

        for(i=0;i<=4;i++) {
            rPoint = Point[i];
            printf("%d\n", rPoint.x);
        }
       system("pause");
       return 0;
    }

Error: 9 C:***\\main.c syntax error before '&' token

C++ does not allow unassigned references, so this is your error:

struct P & rPoint;

If you want reassignment, use a pointer.

int main(int argc, char **argv){
    struct P points[5];
    struct P* point;

    int i;
    for(i=0;i<=4;i++) {
        point = points + i; // or &points[i]
        point->x = i;
    }
    // ...

C++ references don't work like that. You have to initialize the reference when you define it. So something like:

int x = 5;
int &r = x;   // Initialise r to refer to x

Also, you can't "re-seat" a reference; it will always refer to the same variable. So continuing the above example:

int x = 5;
int y = 10;
int &r = x;

r = y;  // This will not re-seat y; it's equivalent to x = y

Error: 9 C: * \\main syntax error before '&' token 语法错误

Besides what the others said, you are compiling it as a C file, and in C references do not exist. Give it a .cpp extension if you want to compile it as C++, or make point a pointer instead of a reference (actually, you'll have to make it a pointer anyway, since you can't reseat a reference).

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