NO

Author Topic: Literal Values  (Read 3334 times)

boral

  • Guest
Literal Values
« on: June 13, 2012, 08:01:44 PM »
I am learning C#.......there I found the term Literal Values.....Can anyone please explain in details what are these.

Offline Vortex

  • Member
  • *
  • Posts: 804
    • http://www.vortex.masmcode.com
Code it... That's all...

CommonTater

  • Guest
Re: Literal Values
« Reply #2 on: June 13, 2012, 09:08:49 PM »
I am learning C#.......there I found the term Literal Values.....Can anyone please explain in details what are these.

C# is not C but in this case it overlaps...

X = 46; <-- 46 is a literal value
strcpy(string,"This is a test");   <-- "This is a Test" is a literal value.

Pretty simple really... if you type it into the source code instead of housing it in a variable, it's a literal value.
 
EDIT... OOPS, didn't notice Vortex's answer until I posted mine...
Yes, Wikipedia is an excellent resource for this.

 

boral

  • Guest
Re: Literal Values
« Reply #3 on: June 14, 2012, 05:52:37 AM »
Thanks for your answers. :)

migf1

  • Guest
Re: Literal Values
« Reply #4 on: June 16, 2012, 05:48:53 PM »
... if you type it into the source code instead of housing it in a variable, it's a literal value...

In most languages, literals represent read-only memory. I'm emphasizing on this because a common mistake I come across when viewing code written by newcomers, is the unintentional attempt to modify a string literal, which in C leads to a seg-fault crash.

In its most simple form, assuming an s_tolower(char *s) function ...

Code: [Select]
char *s_tolower( char *s )
{
    register char *ret = NULL;

    /* sanity checks */
    if ( !s )
        return NULL;
    if ( !*s )
        return s;

    for ( ret=s; (*s=tolower(*s)); s++ )
        ;   /* void */

    return ret;
}

we cannot use it with a string-literal as an argument...

Code: [Select]
...
int main( void )
{
    puts( s_tolower("UPPER") );
    exit(0);
}

That produces a seg-fault, since "UPPER" is not allowed to get modified, in any way. It has to be housed into a variable (as tater mentioned) and then passed to the function via that variable....

Code: [Select]
...
int main( void )
{
    char s[] = "UPPER";

    puts( s_tolower(s) );
    exit(0);
 }


You may keep that in mind if you are a newcomer ;)

EDIT:

   char *s = "UPPER";

won't work either, this is read-only memory too.

Variable s has to be initialized with array notation (or defined as a pointer which gets malloc'ed and filled-in before passing it as an argument to the function).


 
« Last Edit: June 16, 2012, 05:53:40 PM by migf1 »