cluelessGowtham
cluelessGowtham

Reputation: 21

const reference syntax difference between visual studio and gcc

#include <iostream>

void swap(float& const a, float& const b)
{}

int main()
{
    std::cout << "Hello, world!\n";
}

This simple code compiles in Visual studio (vs2013) but not in gcc. I have tried c++ 10 and also c++11. gcc gives an error saying

error: 'const' qualifiers cannot be applied to 'float&'

But if I change the function definition to

void swap(float const &a, float const &b)

it compiles in gcc and also visual studio.

My question is, does both these syntaxes mean the same thing? Also, why it compiles with visual studio and not with gcc

Upvotes: 1

Views: 242

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145359

float& const a is invalid. A reference cannot be const. It can refer to a const object but it cannot itself be const (it would be meaningless since it's not reseatable).

C++14 §8.3.2/1:

Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name (7.1.3, 14.1) or decltype-specifier (7.1.6.2), in which case the cv-qualifiers are ignored.

A decltype-specifier is a use of the decltype keyword.


Visual C++ 2015 does warn about it (at warning level 4):

C:\my\forums\so\141> cl foo.cpp /Feb
foo.cpp
foo.cpp(3): warning C4227: anachronism used: qualifiers on reference are ignored
foo.cpp(3): warning C4100: 'b': unreferenced formal parameter
foo.cpp(3): warning C4100: 'a': unreferenced formal parameter

C:\my\forums\so\141> g++ foo.cpp -Wno-unused-parameter
foo.cpp:3:24: error: 'const' qualifiers cannot be applied to 'float&'
 void swap(float& const a, float& const b)
                        ^
foo.cpp:3:40: error: 'const' qualifiers cannot be applied to 'float&'
 void swap(float& const a, float& const b)
                                        ^

C:\my\forums\so\141> _

Upvotes: 4

Related Questions