[Swan-dev] const version of str_*()

D. Hugh Redelmeier hugh at mimosa.com
Mon Sep 16 15:07:02 UTC 2019

| From: D. Hugh Redelmeier <hugh at mimosa.com>

| I don't think that C guarantees that the id_buf value would live long
| enough.  The expression is more explicitly written
| 	&id_str(&id1).buf[0]
| As soon as the & is applied, I believe that C's semantics allows the
| temporary id_buf value to be discarded by the implementation.  Before
| the pointer is passed to printf.  So the pointer must not be
| dereferenced.  Thus this code probably ventures into the dreaded
| "undefined behaviour".

A simpler way of looking on this:
The result of a function is a value, not an object.
You cannot take the address of a value.
The result of a function has no lvalue.

This apparently simple rule has exceptions.  One would think that a
string literal would be a value.  But in almost all uses you do take
its address.  (There are two exceptions to this exception: sizeof and
the initializer for a char array object.)

More information about the Swan-dev mailing list