top button
Flag Notify
Site Registration

In C++, How compiler decides the size of a variable of string data type?

+2 votes
682 views

Below is the sample code, Where size of a is not defined at the time of compilation,
Then how compiler knows the size of a? If we run the same program in C then compilation will fail.

#include<iostream>
using namespace std;
main()
{
        string a;
        cin>>a;
        cout<<a;
}
posted Apr 25, 2016 by Chirag Gangdev

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Are you looking for str.length() which returns the length of string.
No Sir,
What I am asking is how compiler will know how many bytes to reserve for that variable,
In C, if we compile a code " char a[];"
Then it will give compile time error, because compiler doesn't know how much to reserve for that variable, same way in c++ its not happening
hey chirag,read this article, perhaps u get something related your question,
http://cs.stmarys.ca/~porter/csc/ref/c_cpp_strings.html

1 Answer

0 votes

Hi,First of all you wrote this in cpp language,It is not going to compile on C and have you used ever c++14 or standard template library while programming with c++? I ran your program in c++14 using header library stdc++.h.
see this

#include<bits/stdc++.h>
using namespace std;
main()
{
        string a;
        cin>>a;
        cout<<a;
        cout<<a.size();
}

Online Compiled Successfully,check here: https://ideone.com/Ep52vB
Now according to your ques that how the compiler will know the size of variable a in bytes while compile time then consider some facts with string data type in c++
"while getting input from terminal,you can enter as many character inputs/string whether it is combination of [a-z,A-Z] or symbols,it will store them by reserving 1 byte each character/symbol but string datatype handle bytes without knowledge of the encoding that may eventually be used to encode the characters it contains. Therefore, the value returned may not correspond to the actual number of encoded characters in sequences of multi-byte or variable-length characters "
I tried with some possible combination of inputs example -
input: ShivamKumarPandey
size= 17 bytes
input: 123456789
size= 9 bytes
you check the size of a at any time by using

VariableName.size() ;

So the size of a is depends on how many characters are in a while giving input. It is not like int/float/double etc where size is already defined. it is dynamic.

answer Apr 30, 2016 by Shivam Kumar Pandey
...