gcccompiler-errors

Why am I getting an error with gcc but not with g++ in Linux


The line of code below is giving an error with the gcc compiler even when this file is saved as check.c. The error is at the line void swap_address(int& a, int& b) as

error: expected ‘;’, ‘,’ or ‘)’ before ‘&’ token

I have used this command to compile the C file: gcc -o check check.c

but the same code is working fine if I use the g++ compiler using: g++ -o check check.c

Please provide me with the reason why it is working for g++ and not for gcc.

The code:

#include <stdio.h>
void swap_value(int a, int b)
{
    a=a+b;
    b=a-b;
    a=a-b;
}
void swap_address(int& a, int& b)
{
    a=a+b;
    b=a-b;
    a=a-b;
}
int main()
{
    int i=5,j=3;    
    swap_value(i,j);
    printf("%d%d\n", i, j);
    swap_address(i,j);
    printf("%d%d\n", i, j);
    return 0;
}

Solution

  • swap_address() has reference parameters the file has a ".c" extension, so gcc is assuming it is a C file and producing an error because reference parameters are not part of C.

    g++ is taking the file as being C++, so it is happy with the reference parameters.