C++ Code explanation

58 views
Skip to first unread message

walirazz...@gmail.com

unread,
Feb 25, 2015, 10:23:57 AM2/25/15
to std-dis...@isocpp.org
Hi ... I have a problem with this code, Please someone explain it 


#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;

int main()
{
int n1;
char n2[0];
cout<<"Enter element 1"<<endl;
cin>>n1;
cout<<"Enter element 2"<<endl;
cin>>n2;
cout<<"Element 2 is "<<n2<<endl;
cout<<"Element 1 is "<<n1<<endl;
getch();
}


when we enter element one say 2 which is int type and after that second say 'a' which is string and then while printing there value 
it prints n1's value the ASCII of n2 not the actual value of n1. someone please explain the reason is there any standard ? 
On the other hand changing the order or declaration as
char n1[0];
int  n2;
it prints the actual value of both. Please explain it reasonably. 
Thanks in advance :)

Thiago Macieira

unread,
Feb 25, 2015, 10:41:14 AM2/25/15
to std-dis...@isocpp.org
On Wednesday 25 February 2015 07:23:57 walirazz...@gmail.com wrote:
> char n2[0];

This is not valid.

8.3.4 Arrays [dcl.arrays] paragraph 1 contains the text
"If the constant-expression (5.19) is present, it shall be a converted
constant expression of type std::size_t and its value shall be greater
than zero."


--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Software Architect - Intel Open Source Technology Center
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358

Vlad from Moscow

unread,
Feb 25, 2015, 11:16:20 AM2/25/15
to std-dis...@isocpp.org, walirazz...@gmail.com

As Thiago has explained this program is invalid.
If you want to know what is behind the scene then it seems the addresses of the character array and integer object coincide.

So when the value (for example "a") of the array was entered it overwrote the value that was entered for n1 in the preceeding step..

Thus at the common address of this two objects there is the same value

96, 0

Then it is outputed at first as a character array and you see character 'a' and then it is outputed as an integer and you see 96.

If you  will change the order of definitions of the objects then the objects do not overlape. Nevertheles the program has undefined behaviour because the data that are entered in the character array overwrite some other memory.
Reply all
Reply to author
Forward
0 new messages