Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading inserters and strange output(for '20' and '020') [duplicate]

i was learning to overload '<<' in a very simple program,& during my study,i found the following surprising output of my program.

#include<iostream>
#include<conio.h>
#include<string>

using namespace std;

class student
{

int age;

 public:
student(){}
student(int a){age=a;}

friend ostream &operator<<(ostream &stream,student o); 
};

 /*operator overloaded in this block*/
 ostream &operator<<(ostream &stream,student o)
{ 
stream<<o.age;
return stream;
}

int main()
{
student ob1(20),ob2(020);   
cout<<ob1;   /*will yield 20(as desired)*/
cout<<"\n"<<ob2;     /*yielding 16(why so)*/
    _getch();
return 0;
 }

any explainations please

like image 320
nobalG Avatar asked Aug 11 '11 13:08

nobalG


2 Answers

0 is the octal prefix for C++ integer literals and 20 in octal is 16 in decimal.

To explain further: If a literal starts with 0 the rest of the number will be interpreted to be in octal representation. In your example 2*8^1 + 0 * 8^0.

The syntax for integer literals is given in §2.14.2 in the most recent standard draft.

like image 108
pmr Avatar answered Nov 10 '22 01:11

pmr


student ob1(20),ob2(020);

You have written 020 which in C and C++ is interpreted as an octal number (base 8) due to the zero at the start. So 020 has the value 16 in decimal.

like image 26
jcoder Avatar answered Nov 10 '22 02:11

jcoder