Saturday, August 11, 2012

The Literal Suffixes and Prefixes of ANSI C

In order to improve the readability of your code , you can declare constant literal values using suffixes.

Also, if you want to initialize integers in other radix than decimal, you can use prefixes. Characters can be as well declared using the octal, decimal and hexadecimal.

Here are some examples:
/*-----------------------------------------------
Integer constants
-----------------------------------------------*/
//A signed integer has no suffix
#define CI_1            (3);
//An unsigned integer has the u or U suffix
#define CUI_1           (3U);
//A long integer has the l or L suffix
#define CLI_1           (3L);
//A long integer has the ul or UL suffix
#define CLUI_1          (3UL);
/*-----------------------------------------------
Real constants
-----------------------------------------------*/
//A float has the f suffix
#define CF_1            (3.0F);
//A double has no suffix
#define CD_1            (3.0);
//A long double has l or L suffix
#define CLD_1           (3.0L);
/*Suffixes can also be added when you operate
  with the scientific notation*/
#define CF_2            (10e-1F);
#define CLD_2           (10e-1L);
/*-----------------------------------------------
Radix-based integer constants
-----------------------------------------------*/
//An octal-radix integer requires the 0 prefix
#define CIO_1           (037);
//A hexadecimal-radix requires the 0x prefix
#define CIH_1           (0x37);
/*The unsigned and long suffixes can be also applied to
  octal and hexadecimal*/
#define CUIO_1          (037U)
#define CLIO_1          (0x37U)
/*-----------------------------------------------
Character constants
-----------------------------------------------*/
//Declaring a character constant
#define CC_1            ('a')
//Defining the character constant using its ASCII code in octal
#define CC_2            ('\141')
//Defining the character constant using its ASCII code in hexadecimal
#define CC_3            ('\x61')
//Defining the character constant using its ASCII code in decimal
#define CC_4            (97)
/*-----------------------------------------------
String constants
-----------------------------------------------*/
//Declaring a string constant
#define CS_1            ("Constant string")
//You can initialize it using multiple smaller strings
#define CS_2            ("Constant " "string")
//You can also initialize it using multiple rows
#define CS_3            ("Constant \
                         string")
There is also a set of predefined character constants, in chapter 6 from the Formatted Strings article.

Question: Do you use constant/rvalue literals in your code?

References:

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger