By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,257 Members | 2,812 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,257 IT Pros & Developers. It's quick & easy.

are strings passed by value or reference ? Output of below pgm not understood.

P: 1
Are strings passed by value or reference?

I don't understand the output of below program.

Expand|Select|Wrap|Line Numbers
  1. #include<iostream.h>
  2. void print(char *p)
  3. {
  4.     p="Pass";
  5.     cout<<"\n value is :"<<p;
  6. }
  7. void main()
  8. {
  9.     clrscr();
  10.     char *q="Best of Luck";
  11.     print(q);
  12.     cout<<"\n New Value is : "<<q;
  13.  
  14. }
The answer is displayed as follows ...
The value is : Pass
New Value is : Best of Luck

Isn't a string passed by reference? Pls explain the reason for this answer .
Jan 8 '17 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
First, everything is passed by value. When you use q to call a function, the function makes a copy called p and assigns the address of "Pass" to p. Now you see p displayed as Pass. Then p is destroyed when the function returns. The calling function uses q in a display and you see Best of Luck.

Nothing is passed by reference unless you use the reference operator with your function argument.

As to strings, a char* is not a string. An old C convention was used to ASSUME a char* was the address of a char array whose last byte was a null (\0).

A C++ string is a class:

Expand|Select|Wrap|Line Numbers
  1. string str;
To use C++ strings you need to study the C++ Standard Library string class.
Jan 8 '17 #2

Post your reply

Sign in to post your reply or Sign up for a free account.