0

Can we use the currency signs like and $ while declaring variable in C++ language? I tried to find the answer on google but I was not clear about it.We can not use special symbols like #,*,% in variable names in c++ language but can we use currency signs like and $ as variable names?

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • No, see [here](https://en.cppreference.com/w/cpp/language/identifiers) – Nimrod Dec 21 '21 at 08:44
  • [Yes](https://godbolt.org/z/f341KhY1q), but it requires compiler support, and it is not standard C++. – 康桓瑋 Dec 21 '21 at 08:49
  • Not in standard C++. That said, some compilers do provide non-standard extensions. But most compilers do not provide such extensions. – Peter Dec 21 '21 at 11:13

1 Answers1

0

You sort of can if you use "user defined literals". https://en.cppreference.com/w/cpp/language/user_literal However not all compilers will be happy with the rupee special character (MSVC accepts it) Example here :

#include <iostream>

struct dollars_t
{
    double value;
};

struct rupees_t
{
    double value;
};

constexpr dollars_t operator "" _$(long double value)
{
    return dollars_t{ static_cast<double>(value) };
};

constexpr rupees_t operator "" _₹(long double value)
{
    return rupees_t{ static_cast<double>(value) };
};


int main()
{
    auto dollars = 10.12_$;
    auto rupees = 1000.12_₹;

    std::cout << "You have " << dollars.value << " dollars\n";
    std::cout << "And you have " << rupees.value << " rupees\n";

    return 0;
}
Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19