Browse thread
Unexpected behaviour of strings initialized with quotes
- Arthur Chargueraud
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Arthur Chargueraud <cours_caml@f...> |
| Subject: | Unexpected behaviour of strings initialized with quotes |
I am surprized by a difference of behaviour between the strings
"bbbb" and (String.make 4 'b').
I have been programming in Caml for a while, and I've always
assumed that the two expression would be rather equivalent.
The idea is that when writing: let f() = "bbbb"
Any call to function f() will return the same string (ie same pointer).
This is of course not the case when writing: let f() = String.make 4 'b'
Below is a program where this behaviour is causing a problem:
code:
for i = 0 to 3 do
let s = "bbbb" in
s.[i] <- 'a';
Printf.printf "string s is now %s\n" s;
done;
outputs:
string s is now abbb
string s is now aabb
string s is now aaab
string s is now aaaa
What it means is that this code is just equivalent to:
let s = "bbbb" in
for i = 0 to 3 do
s.[i] <- 'a';
Printf.printf "string s is now %s\n" s;
done;
which I find really unexpected. I was waiting for:
string s is now abbb
string s is now babb
string s is now bbab
string s is now bbba
which is what happens when using (String.make 4 'b') inside the loop.
This is not a real problem, since it is not usual to modify
strings initialized with quotes, but I am just wandering
about the reason of such a behaviour...
Arthur Chargueraud