News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

Literal Values

Started by boral, June 13, 2012, 08:01:44 PM

Previous topic - Next topic

boral

I am learning C#.......there I found the term Literal Values.....Can anyone please explain in details what are these.


CommonTater

Quote from: boral 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.

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

Thanks for your answers. :)

migf1

#4
Quote from: CommonTater on June 13, 2012, 09:08:49 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 ...


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...


...
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....


...
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).