delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/27/23:02:23

Date: Wed, 27 Aug 1997 20:00:57 -0700 (PDT)
Message-Id: <199708280300.UAA10571@adit.ap.net>
Mime-Version: 1.0
To: djgpp AT delorie DOT com
From: Nate Eldredge <eldredge AT ap DOT net>
Subject: Re: [Q] using int 0x21 to print text with inline asm

All right, let's settle this once and for all. K&R page 186, in section 7.1,
says:
 A string is a primary expression. Its type is originally "array of char";
but following the same rule given above for identifiers, this is modified to
"pointer to char" and the result is a pointer to the first character in the
string. (There is an exception in certain initializers, see [section]8.6.)
[This exception involves initializing an array with a string.]

So the expression "Hello, world!" is of type "array of char" or char[]. This
decays to "pointer to char" or char *. Since, in the example, myHappy was
declared as a char *, it is certainly legal to assign an expression of type
"char *" to a variable of type "char *". If the line given was inside a
function, this is the case.
If it were at the top level, it would be an initialization. Variables can be
initialized with constant values that are known at compile time. "Hello,
world!" is obviously a constant-value expression, and a pointer variable can
be initialized with its address.

So all of the following are legal:
/* Top level */
char s[] = "Hello";
-- and --
/* Top level */
char *s = "Hello";
-- and --
char *s;
void f()
{
   s = "Hello";
}

More importantly, GNU C generates the proper code for each.

At 08:36  8/26/1997 GMT, Andrew Cheyne wrote:
>Cesar Scarpini Rabak (csrabak AT dce03 DOT ipt DOT br) wrote:
>: At 23:35 25/08/97 GMT, firewind wrote:
>: >> myHappy = "Hello, world!";
>: >  ^^^^^^^^^^^^^^^^^^^^^^^^^^ (3)
>: >3: you're assiging a string to a variable, but this string really has no
>: >   storage allocated for it.
>: >
>: This affirmation is incorrect! What this line of code does is to
>: _initialize_ the pointer myHappy with the address of the first element of
>: the constant array of char _"Hello, world!"_. Nothing particular wrong there.
>  Actually, he was correct. You cant initialize a pointer to point to
>something if you dont allocate memory for it. You CAN say
>char* myHappy = "Hello, world!";
>but that is different than:
>char* myHappy;
>myHappy = "Hello, World!";

Is everybody happy now?

Nate Eldredge
eldredge AT ap DOT net



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019