473,796 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

string constant

hello everybody,

consider the following statement,
char *s = "someString ";

Does the above statement cause "someString " to be alloted a constant
memory space. What I mean is can't we manipulate "someString " using
statements like

s[0] = 'a';

Oct 20 '06 #1
6 1638
chandanlinster <ch************ @gmail.comwrote :
consider the following statement,
char *s = "someString ";
Does the above statement cause "someString " to be alloted a constant
memory space.
It might; implementations are allowed to make this choice for
themselves.
What I mean is can't we manipulate "someString " using
statements like
s[0] = 'a';
No. Not portably, at least, although some implementations offer the
ability to modify string literals as an extension.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Oct 20 '06 #2
"chandanlinster " <ch************ @gmail.comwrite s:
consider the following statement,
char *s = "someString ";

Does the above statement cause "someString " to be alloted a constant
memory space. What I mean is can't we manipulate "someString " using
statements like

s[0] = 'a';
No, attempting to modify a string literal invokes undefined behavior.

(For historical reasons, string literals are not treated as "const";
attempting to modify one invokes UB because the standard says so
explicitly.)

Some implementations may allow you to do this. Don't.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 20 '06 #3
Keith Thompson wrote:
"chandanlinster " <ch************ @gmail.comwrite s:
>>consider the following statement,
char *s = "someString ";

Does the above statement cause "someString " to be alloted a constant
memory space. What I mean is can't we manipulate "someString " using
statements like

s[0] = 'a';


No, attempting to modify a string literal invokes undefined behavior.

(For historical reasons, string literals are not treated as "const";
attempting to modify one invokes UB because the standard says so
explicitly.)
But it's still worth declaring them as const.

--
Ian Collins.
Oct 20 '06 #4
Ian Collins <ia******@hotma il.comwrites:
Keith Thompson wrote:
>"chandanlinste r" <ch************ @gmail.comwrite s:
>>>consider the following statement,
char *s = "someString ";

Does the above statement cause "someString " to be alloted a constant
memory space. What I mean is can't we manipulate "someString " using
statements like

s[0] = 'a';


No, attempting to modify a string literal invokes undefined behavior.

(For historical reasons, string literals are not treated as "const";
attempting to modify one invokes UB because the standard says so
explicitly.)
But it's still worth declaring them as const.
Yes.

More pedantically, if you have an array whose initializer is a string
literal, it's a good idea to declare the array as const.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 20 '06 #5
Keith Thompson wrote:
Ian Collins <ia******@hotma il.comwrites:
>>Keith Thompson wrote:
>>>"chandanlins ter" <ch************ @gmail.comwrite s:
consider the following statement,
char *s = "someString ";

Does the above statement cause "someString " to be alloted a constant
memory space. What I mean is can't we manipulate "someString " using
statement s like

s[0] = 'a';
No, attempting to modify a string literal invokes undefined behavior.

(For historical reasons, string literals are not treated as "const";
attempting to modify one invokes UB because the standard says so
explicitly .)

But it's still worth declaring them as const.


Yes.

More pedantically, if you have an array whose initializer is a string
literal, it's a good idea to declare the array as const.
Wouldn't that depend on the purpose of the array?

/* const ??? */ char devname[] = "/dev/pty?";
char *p = strchr(devname, '?');
char *q;
FILE *stream;
for (q = "abc"; *q != '\0'; ++q) {
*p = *q;
stream = fopen(devname, "r+");
if (stream != NULL)
return stream;
}
return NULL;

In my experience, an explicit array is initialized with a
string literal only when one *does* want to modify it; if one
does not, one simply uses the literal. Do you write

const char message[] = "Hello, world!";
puts (message);

or simply

puts ("Hello, world!");

?

--
Eric Sosman
es*****@acm-dot-org.invalid
Oct 21 '06 #6
Eric Sosman <es*****@acm-dot-org.invalidwrit es:
Keith Thompson wrote:
[...]
>More pedantically, if you have an array whose initializer is a string
literal, it's a good idea to declare the array as const.

Wouldn't that depend on the purpose of the array?
[snip]

Yes, sorry, I goofed.

If you have a *pointer* whose initializer is a string literal, you
should declare it as const:

const char *p = "hello";

If you have an *array*, declare it as const or not depending on how
you want to use it; the initializer is irrelevant:

char arr[] = "hello";

Here, the string literal is (logically) *copied* to the array. In the
first case, the pointer actually points to the string literal itself.
More precisely, the string literal causes an anonymous array of static
storage duration, just large enough to hold the sequence of
characters, to be created. The pointer points to this array. Any
attempt to modify the array invokes UB.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 21 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

51
8299
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
21
5760
by: M D | last post by:
You know how you assume you know until you find out you don't know. Well, I typed into a function definition "..., new String("")). I know what I want. Everyone reading this knows what I want. However, the 1.0 compiler has no idea what I want. Can anyone share with me the syntax that will actually communicate the concept to the compiler, please?
34
1902
by: Chad | last post by:
Given the following code that achieves no useful purpose: #include <string.h> #include <stdio.h> #include <string.h> int manip(char *str) { size_t len = strlen(str)-1; if(len >= 3) {
14
1860
by: nospam | last post by:
From the book "There is an important difference between these definitions: char amessage="now is the time"; char *pmessage ="now is the time"; snip On the other hand, pmessage is a pointer, initialized to point a string const; the pointer may be modified to point elsewhere, but the
20
691
by: karthikbalaguru | last post by:
Hi, String constant being modifiable in C++ but, not modifiable in C. that is, In C++, the following example output will be "Mplusplus" char *str1 = "Cplusplus"; *str1 = 'M'; In C, the above example will produce an error as we are trying to modify a constant. So, str1 is not a string constant in C++.
18
1931
by: sinbad | last post by:
hi, why does the following program gives an runtime error ,instead of compilation error. anyone please shed some light. thanks sinbad ------------------------------ int main()
13
21853
by: sinbad | last post by:
hi, how to concatenate a "hash defined" constant value to another "hash defined" constant string. For example #define ABC 100 #define MYSTR "The value of ABC is" Now i need a string that will concatenate the value of ABC to MYSTR . I need this at compile time.
21
1463
by: Ray Cassick | last post by:
I can't believe why I had not noticed this before and why I never asked it before... When defining a string why is it not required to use the new keyword? Like: Dim a As String = New String You can do it when using the string type with some arguments in the constructor but it look like there is no empty constructor on the String class.
1
2426
by: mohanprasadgutta | last post by:
hello everyone, i have to write a program which will take a command line arguement which is nothing but a constant name. in the program i am trying to print out the value corresponding to the constant name provided. i am aware of converting a string to a variable name as follows. my $name = "mohan"; my $var = "name"; my $new = $$name; print "your name is : " . $name . "\n"; But here i have to get the constant value corresponding to...
7
4269
by: Hendrik Schober | last post by:
Hi, this #include <string> class test { typedef std::string::size_type size_type; static const size_type x = std::string::npos; }; doesn't compile using either VC9 ("expected constant expression") or Comeau Online ("constant value is not known"). If I replace
0
9679
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10453
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10172
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9050
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6785
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5441
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.