Skip to main content

Variables and Constants in C

Variables
In programming, a variable is a container (storage area) to hold data.To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. For example:

int playerScore = 95;

Here, playerScore is a variable of integer type. The variable is assigned value: 95.
The value of a variable can be changed, hence the name 'variable'.
In C programming, you have to declare a variable before you can use it.
 
Rules for naming a variable in C
 
A variable name can have letters (both uppercase and lowercase letters), digits and underscore only.

The first letter of a variable should be either a letter or an underscore. However, it is discouraged to start variable name with an underscore. It is because variable name that starts with an underscore can conflict with system name and may cause error.

There is no rule on how long a variable can be. However, only the first 31 characters of a variable are checked by the compiler. So, the first 31 letters of two variables in a program should be different.

C is a strongly typed language. What this means it that, the type of a variable cannot be changed.
 
Constants/Literals
 
A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5, "C programming is easy", etc.

As mentioned, an identifier also can be defined as a constant.
const double PI = 3.14
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
There are four basic types of constants in C. They are
  • integer constants
  • floating-point constants
  • character constants
  • string constants
there are also enumeration constants, which are discussed later .

Moreover, there are several different kinds of integer and floating-point constants, as discussed below.
Integer and floating-point constants represent numbers. They are often referred to collectively as numeric-type constants. The following rules apply to all numeric-type constants.

1. Commas and blank spaces cannot be included within the constant.
2. The constant can be preceded by a minus (-) sign if desired. (Actually the minus sign is an operator that changes the sign of a positive constant, though it can be thought of as a part of the constant itself.)
3. The value of a constant cannot exceed specified minimum and maximum bounds. For each type of
constant, these bounds will vary from one C compiler to another.

1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional or exponential part. There are three types of integer constants in C programming:
  • decimal constant(base 10)
  • octal constant(base 8)
  • hexadecimal constant(base 16)

For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x(0X).

 Unsigned integer constants may exceed the magnitude of ordinary integer constants by approximately a factor of 2, though they may not be negative. An unsigned integer constant can be identified by appending the letter U (either upper- or lowercase) to the end of the constant.
Long integer constants may exceed the magnitude of ordinary integer constants, but require more memory within the computer. With some computers (andor some compilers), a long integer constant will automatically be generated simply by specifying a quantity that exceeds the normal maximum value. It is always possible, however, to create a long integer constant by appending the letter L (either upper- or lowercase) to the end of the constant.
An unsigned long integer may be specified by appending the letters UL to the end of the constant. The
letters may be written in either upper- or lowercase. However, the U must precede the L.
Several unsigned and long integer constants are shown below
Constant                     Number System
50000U                       decimal (unsigned)
123456789L               decimal (long)
123456789UL            octal (long)
077777711                  octal (unsigned)
0X50000U                  hexadecimal (unsigned)
0XFFFFFUL               hexadecimal (unsigned long)


2. Floating-point constants
Afloating-point constant is a base- 10 number that contains either a decimal point or an exponent (or both).
Several valid floating-point constants are shown below.
0.     1 .         0.2         827.602
50000.         0.000743             12.3                     315.0066
2E-8             0.006e-3             1.6667E+8         .12121212e12

The interpretation of a floating-point constant with an exponent is essentially the same as scientific notation, except that the base 10 is replaced by the letter E (or e). Thus, the number 1.2 x 10^-3 would be written as 1 .2E-3 or 1 .2e-3. This is equivalent to 0.12e-2, or 12e-4, etc.

The quantity 3 x 10^5can be represented in C by any of the following floating-point constants.

300000.     3e5     3e+5     3E5             3.Oe+
.3e6         0.3E6     30E4     30. E+4     300e3

Similarly, the quantity 5.026 x 10^-l7 can be represented by any of the following floating-point constants.
5.026E-17         .5026e-16         50.26e-18         .0005026E-13

Floating-point constants are normally represented as double-precision quantities in C. Hence, each floating-point constant will typically occupy 2 words (8 bytes) of memory. Some versions of C permit the specification of a “single-precision,” floating-point constant, by appending the letter F (in either upper- or lowercase) to the end of the constant (e.g., 3E5F). Similarly, some versions of C permit the specification of a “long” floating-point constant, by appending the letter L (upper- or lowercase) to the end of the constant (e.g.,0.123456789E-33L).

3. Character constants
A character constant is a constant which uses single quotation around characters.A character constant is a single character, enclosed in apostrophes (i.e., single quotation marks).

For example: 'a', 'l', 'm', 'F', ' '( blank space)
Most computers, and virtually all personal computers, make use of the ASCII (i.e., American Standard Code for Information Interchange) character set, in which each individual character is numerically encoded with its own unique 7-bit combination (hence a total of 2' = 128 different characters).
Example:
Character    ASCII value
'A'                  65
'a'                   97
'0'                   48
 
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the characters are interpreted by the compiler.
Escape Sequences
Character
\b
Backspace
\f
Form feed
\n
Newline
\r
Return
\t
Horizontal tab
\v
Vertical tab
\\
Backslash
\'
Single quotation mark
\"
Double quotation mark
\?
Question mark
\0
Null character    

Of particular interest is the escape sequence \0. This represents the null character (ASCII 000), which is
used to indicate the end of a string (see below). Note that the null character constant \0 is not equivalent to the character constant '0' .
An escape sequence can also be expressed in terms of one, two or three octal digits which represent single-character bit patterns. The general form of such an escape sequence is \ooo, where each o represents an octal digit (0through 7). 

Some versions of C also allow an escape sequence to be expressed in terms of one or more hexadecimal digits, preceded by the letter x. The general form of a hexadecimal escape sequence is \xhh, where each h represents a hexadecimal digit (0 through 9 and a through f). The letters can be either upper- or lowercase. The use of an octal or hexadecimal escape sequence is usually less desirable than writing the character constant directly, however, since the bit patterns may be dependent upon some particular character set.
The letter A is represented by the decimal value 065 in the ASCII character set. This value is equivalent to the octal value 101. (The equivalent binary bit pattern is 001 000 001.) Hence the character constant   ' A ' can be expressed as the octal escape sequence ' \ 101'.In some versions of C, the letter A can also be expressed as a hexadecimal escape sequence. The hexadecimal equivalent of the decimal value 65 is 41. (The equivalent binary bit pattern is 0100 0001.) Hence the character constant ' A ' can be expressed as ' \x41 I , or as ' \X41 ' .

4. String constants
A string constant consists of any number of consecutive characters (including none), enclosed in (double) quotation marks.
For example:

"good"     //string constant
""             //null string constant
"    " //string constant of  white spaces
"x" //string constant having single character
"Earth is round\n" //prints string with newline
Note that the string constant "Line 1\nLine 2\nLine 3" extends over three lines, because of the newline characters that are embedded within the string. Thus, this string would be displayed as
Line 1
Line 2
Line 3
Also, notice that the string " " is a null (empty) string.

The following string constant includes three special characters that are represented by their corresponding escape sequences.
" \ t T o continue, press the \"RETURN\" key\n"
The special characters are \t (horizontal tab), \ I' (double quotation marks, which appears twice), and \ n (newline).

The compiler automatically places a null character (\0) at the end of every string constant, as the last character within the string (before the closing double quotation mark). This character is not visible when the string is displayed. However, we can easily examine the individual characters within a string, and test to see whether or not each character is a null character  Thus, the end of every string can be readily identified. This is very helpful if the string is scanned on a character-by-character basis, as is required in many applications. Also, in many situations this end-of-string designation eliminates the need to specify a maximum string length.

Remember that a character constant (e.g., I A I ) and the corresponding single-character string constant ("A") are not equivalent. Also remember that a character constant has an equivalent integer value, whereas a single-character string constant does not have an equivalent integer value and, in fact, consists of two characters -the specified character followed by the null character ( \0).


5. Enumeration constants
Keyword enum is used to define enumeration types. 
 
For example:
enum color {yellow, green, black, white};

Here, color is a variable and yellow, green, black and white are the enumeration constants having value 0, 1, 2 and 3 respectively.
If we do not explicitly assign values to enum names, the compiler by default assigns values starting from 0.

Two enum names can have same value. For example, in the following both ‘Failed’ and ‘Freezed’ have same value 0.

enum State {Working = 1, Failed = 0, Freezed = 0};

We can assign values to some name in any order. All unassigned names get value as value of previous name plus one.
enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday};
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday, saturday);
The above print statement will print
1 2 5 6 10 11 12 
 
The value assigned to enum names must be some integral constant, i.e., the value must be in range from minimum possible integer value to maximum possible integer value.

All enum constants must be unique in their scope. For example, the following program fails in compilation.
enum state {working, failed};
enum result {failed, passed};
 
Enum vs Macro
We can also use macros to define names constants.
#define sun 0
#define mon 1
#define tue 2
 
There are multiple advantages of using enum over macro when many related named constants have integral values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values. Following is simpler
enum days {sun,mon,tue};

Symbolic Constants

A symbolic constant is a name that substitutes for a sequence of characters. The characters may represent a numeric constant, a character constant or a string constant. Thus, a symbolic constant allows a name to appear in place of a numeric constant, a character constant or a string. 

When a program is compiled, each occurrence of a symbolic constant is replaced by its corresponding character sequence.Symbolic constants are usually defined at the beginning of a program. The symbolic constants may then appear later in the program in place of the numeric constants, character constants, etc. that the symbolic constants represent.

A symbolic constant is defined by writing
#define name text
where name represents a symbolic name, typically written in uppercase letters, and text represents the sequence of characters that is associated with the symbolic name. Note that text does not end with a semicolon, since a symbolic constant definition is not a true C statement. Moreover, if text were to end with a semicolon, this semicolon would be treated as though it were a part of the numeric constant, character constant or string constant that is substituted for the symbolic name.

EXAMPLE 
 A C program contains the following symbolic constant definitions.
#define TAXRATE 0.23
#define P I 3.141593
#define TRUE 1
#define FALSE 0
#define FRIEND "Susan"

Notice that the symbolic names are written in uppercase, to distinguish them from ordinary C identifiers. Also, note that the definitions do not end with semicolons.

Now suppose that the program contains the statement
area = PI * radius * radius;
During the compilation process, each occurrence of a symbolic constant will be replaced by its corresponding text. Thus,the above statement will become

area = 3.141593 * radius * radius;

Symbolic constants are not required when writing C programs. Their use is recommended, however, since they contribute to the development of clear, orderly programs. For example, symbolic constants are more readily identified than the information that they represent, and the symbolic names usually suggest the significance of their associated data items. Furthermore, it is much easier to change the value of a single symbolic constant than to change every occurrence of some numerical constant that may appear in several places within the program.

The #define feature, which is used to define symbolic constants, is one of several features included in
the C preprocessor.



Comments

  1. Thanks a lot for the useful post. Keep updating. It really helped me get my work done.

    C++ Training in Chennai | C Language Training in Chennai

    ReplyDelete
  2. Thanks for this blog. You described each and every basic topic very well. Keep sharing more notes like this.

    Big Data Certification in Pune
    Big Data Testing Classes

    ReplyDelete
  3. Your articles are very useful. They give me a lot of information. I may learn knowledge from them. I can't help reading your posts. It's very kind of you to share your insight. I really like your pieces of writing. They help me so much. Thanks a million. I am waiting new posts. Đăng ký VD300 VinPhone, Đăng ký MAXSV2 VinaPhone, Đăng ký 3G VinaPhone 1 ngày

    ReplyDelete
  4. Looking forward to reading more. Great blog.Really looking forward to read more. Keep writing
    sale notification website 2018
    sales pop master online

    ReplyDelete
  5. Looking forward to reading more. Great blog.Really looking forward to read more. Keep writing
    Discount master app


    Discount master app

    ReplyDelete
  6. For space outside the milk tea shop closer to nature, outdoor space should use speakers with greater capacity, products such as garden speakers, imitation stone speakers, are products with designs The most natural to create interesting feeling when enjoying. Because it must work in the weather conditions heat so the shell is made very firmly with high durability, the quality of the speaker is imported genuine. Good sound, making good clear sound even when used in wide space
    Gái gọi Mỹ Đình - Đình Thôn, gái gọi Nguyễn Khánh Toàn, gái gọi hà nội, gái gọi Phố Cổ - Quán Sứ

    ReplyDelete
  7. Looking forward to reading more. Great blog.Really looking forward to read more. Keep writing
    app autoketing
    https://apps.shopify.com/shipping-bar-master
    https://bit.ly/2BXG37u

    ReplyDelete
  8. This is really a good source of information, I will often follow it to know more information and expand my knowledge, I think everyone should know it, thanks
    currency converter free, currency converter portable, autoketing

    ReplyDelete
  9. i appreciate your article...do have a look on Website Designing In Bangalore India. Static Website Designing is a simple mean of showing information of themselves or any organization.
    C and C++ Training Institute in chennai | C and C++ Training Institute in anna nagar | C and C++ Training Institute in omr | C and C++ Training Institute in porur | C and C++ Training Institute in tambaram | C and C++ Training Institute in velachery

    ReplyDelete

Post a Comment

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar