Why doesn't my code work? It's about reference variable.

0 Nayab Basha Sayed · October 2, 2015
#include <iostream>

using namespace std;

int main()
    char & b = '\n';
    cout << "hello" << b << "world" << b;
    return 0;

I've read in some text book that "char & b = '\n'" creates char object with name b and value \n (There is only one reference b and no variable in the program). But here it is showing error.

error: invalid initialization of non-const reference of type 'char&' from an rvalue of type 'char'.

What should I include to make it work?

Post a Reply


Oldest  Newest  Rating
0 Vincent Gizzarelli · October 2, 2015
Get rid of the '&' and instead make it
int main() {
   char b = "\n";
   //Place cout statement here
   return 0;

 hope this helps!
0 ariel bitan · October 4, 2015
When you put this & it means that you can "control" another variable.
I'll explain,lets say you write:
char a='h';
char b=a;
Now if you'll change b,a will also change,if you'll write b='c' and then you'll write cout<<b it will display c.
Hope this helps
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator