Sunday, 28 August 2011

Qu 12. What is variable? Explain rules how to declair and intilisation a variable

Variable

A variable is a named memory, that can be used to read and write information. In this sense, variables are nothing more than "buckets" that can be used to store whatever values are needed for a specific computation. However, as different materials require different containers, we also have different types of variables for the various contents that can be stored in it.



Declare Variable initialization

There are two C Standards documents. The original (ANSI-89/ISO-90) did not allow mixed declarations and (executable) code within a block. In fact declarations can occur at the beginning of any block (that is, after the opening { brace and before any code), not just at the beginning of a function. This has been true of all releases of any serious compilers, even before the first standard. This standard is sometimes called C89, and sometimes it's called C90.

CPP / C++ / C Code:
#include <stdio.h>
int main()
{
    int i = 1;
    printf("i = %d\n", i);
    {
        int j = 2;
        printf("i = %d, j = %d\n", i, j);
    }
    return 0;
}

Output:
Code:
i = 1 i = 1, j = 2

The variable j is only visible inside the block in which it is declared. This behavior was also carried forward into C++, so the above program is legal C and C++ for all compilers that I have tested (and all C and C++ compilers should work with that code).

There is a second standard, ISO-99, which allows declarations just about anywhere in a block. (This is commonly called the C99 Standard.)

Many commonly used compilers (Borland and Microsoft to name two with I am familiar) do not allow the mixed declarations of the ISO-99 standard.

So the following would not work with these C compilers, but it would be OK with GNU gcc:
CPP / C++ / C Code:
#include <stdio.h>
int main()
{
    int i = 99;
    printf("i = %d\n", i);
    int j = 42;
    printf("j = %d\n", j);
    return 0;
}
 Rules

• Variable name may be a combination of alphabets, digits or underscores.
 
• Sometimes, compilers in which case its length should not exceed 8 characters impose an additional constraint on the number of characters in the name.
 
• First character must b e alphabet or an underscore.
 
• No. comma or blank space is allowed.
 
• Among the special symbols, only underscore can be used in variable name.
 
• No word, having a reserved meaning in C can be used for variable name.
  


No comments:

Post a Comment