Questions on Variables in C Language
1. What is a variable in C language?
Variables are memory location in computer’s memory to store data. To indicate the memory location, each variable should be given a unique name called identifier. Variable names are just the symbolic representation of a memory location. Examples of variable name are sum, car_no, count etc.
Here, num is a variable of integer type.
2. Give the rules for variable declaration?
The rules for variable declaration in C are given below:
• A variable name consists of alphabets, digits and the underscore (_) character.
• The length of variable should be kept upto 8 characters though your system may allow upto 40 characters.
• They must begin with an alphabet.
• Some systems also recognize an underscore as the first character.
• White space and commas are not allowed.
• Any reserved word (keyword) cannot be used as a variable name.
3. How to declare a variable in C language?
All variables must be declared before we use them in C program, although certain declarations can be made implicitly by content. To declare a variable you specify its name and data type it can store. The variable declaration always ends with a semicolon (;) A declaration specifies a type, and contains a list of one or more variables of that type as follows:
Here, type must be a valid C data type including char, int, float, double, or any user defined data type etc., and variable_list may consist of one or more identifier names separated by commas. A variable can be declared multiple times in a program, but it must be defined only once. Some valid variable declarations along with their definition are shown here:
int i, j, k;
char c, ch;
float f, salary;
4. How to assign values to a variable?
A variable can be considered as a box that can hold a single value. However, initially the content of a variable (or a box) is empty. Therefore, before one can use a variable, it must receive a value. Do not assume the compiler or computer will put some value, say 0, into a variable. There are at least three ways to put a value into a variable:
• initializing it when the program is run
• using an assignment statement
• reading a value from keyboard or other device with a READ statement.
Variables may have values assigned to them through the use of an assignment statement.
Such a statement uses the assignment operator =
This operator does not denote equality. It assigns the value of the right-hand side of the statement (the expression) to the variable on the left-hand side.
Diameter = 5.9;
Area = length * width;
Note that only single variables may appear on the left-hand side of the assignment operator
Initializing a variable is only done exactly once when the computer loads your program into memory for execution. That is, all initializations are done before the program starts its execution. The use of un-initialized variables may cause unexpected result.
Some examples are:
Int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = ‘x'; /* the variable x has the value ‘x’. */
5. What is the difference between declaring a variable and defining a variable?
Declaration of a variable in C hints the compiler about the type and size of the variable in compile time. Similarly, declaration of a function hints about type and size of function parameters. No space is reserved in memory for any variable in case of declaration. Example: int a; Here variable ‘a’ is declared of data type ‘int’ Defining a variable means declaring it and also allocating space to hold it. We can say “Definition = Declaration + Space reservation”. Example: int a = 10; Here variable “a” is described as an int to the compiler and memory is allocated to hold value 10.
6. Define the term Scope, Visibility and Lifetime of a Variable?
The scope of a variable is the range of program statements that can access that variable. The lifetime of a variable is the interval of time in which storage is bound to the variable. A variable is visible within its scope and invisible or hidden outside it.
7. What are the different types of variables depending on variable scope?
Depending on the scope of variables in c language, variables could be classified as follows:
Global variables in C have their declaration outside the function definition of all functions used within the program and remains in the memory as long as the program is executing.
All global variables in c could be accessed from anywhere in program which means that any expression in the program can access the global variable regardless of what block that expression is written.
Thus, the global variables have their scope global.
Local variables are declared with in a function definition and thus could only be accessed from anywhere in that function in which it is declared. Thus, local variables have their scope local to the function in which they are declared and are unknown to other functions outside their own function.
Local variables are defined and initialized every time a function containing them is called and as soon as the compiler exits from that function, the local variable is destroyed.
8. What is a storage class in C language?
A storage class is an attribute that tells us where the variable would be stored, what will be the initial value of the variable if no value is assigned to that variable, life time of the variable and scope of the variable.
9. What are different types of storage classes in C language?
Storage class tells us:
• Where the variable is stored.
• Initial value of the variable.
• Scope of the variable. Scope specifies the part of the program which a variable is accessed.
• Life of the variable.
There are four storage classes in C:
• Automatic storage class
• Register storage class
• Static storage class
• External storage class
10. What is an automatic storage class in C language?
The keyword for automatic storage class is auto. Variables declared inside the function body are automatic by default. These variables are also known as local variables as they are local to the function and don’t have meaning outside that function since, variable inside a function is automatic by default, keyword auto are rarely used.
11. Where is the auto variable stored?
Auto variables can be stored anywhere, so long as recursion works. Practically, they’re stored on the stack. It is not necessary that always a stack exist. You could theoretically allocate function invocation records from the heap.
12. What are the advantages of auto variables?
• The same auto variable name can be used in different blocks.
• There is no side effect by changing the values in the blocks.
• The memory is economically used.
• Auto variables have protection because of local scope.
13. What are register variables? What are the advantages of using register variables?
If a variable is declared with a register storage class, it is known as register variable. The register variable is stored in the CPU register instead of main memory. Frequently used variables are declared as register variable as its access time is faster.
14. What does static variable mean?
Static variables are the variables which retain their values between the function calls. They are initialized only once their scope is within the function in which they are defined.
15. What is external storage class?
External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables. In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file.
16. Can static variables be declared in a header file?
You cant declare a static variable without defining it as well (this is because the storage class modifiers static and extern are mutually exclusive). A static variable can be defined in a header file, but this would cause each source file that included the header file to have its own private copy of a variable, which is probably not what was intended.
17. Is it acceptable to declare/define a variable in a C header?
A global variable that must be accessed from more than one file can and should be declared in a header file. In addition, such a variable must be defined in one source file. Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable.
The ANSI C standard will allow multiple external definitions, provided that there is only one initialization. But because there’s really no advantage to using this feature, it’s probably best to avoid it and maintain a higher level of portability.
“Global” variables that do not have to be accessed from more than one file should be declared static and should not appear in a header file.
18. What is a pointer variable?
A pointer variable is a variable that may contain the address of another variable or any valid address in the memory.
19. What are different types of type Qualifiers in C language?
The keywords which are used to modify the properties of a variable are called type qualifiers.
There are two types of qualifiers available in C language. They are,
20. What is const qualifier in C language?
• Constants are also like normal variables. But, only difference is, their values can’t be modified by the program once they are defined.
• They refer to fixed values. They are also called as literals.
• They may be belonging to any of the data type.
const data_type variable_name; (or) const data_type *variable_name;
21. What is volatile qualifier in C language?
• When a variable is defined as volatile, the program may not change the value of the variable explicitly.
• But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile.
• For example, if global variable’s address is passed to clock routine of the operating system to store the system time, the value in this address keep on changing without any assignment by the program. These variables are named as volatile variable.
volatile data_type variable_name; (or) volatile data_type *variable_name;
22. Can a variable be both const and volatile?
Yes. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code. For instance, the timer structure was accessed through a volatile const pointer. The function itself did not change the value of the timer, so it was declared const. However, the value was changed by hardware on the computer, so it was declared volatile. If a variable is both const and volatile, the two modifiers can appear in either order.
23. When should the volatile modifier be used?
The volatile modifier is a directive to the compiler’s optimizer that operations involving this variable should not be optimized in certain ways. There are two special cases in which use of the volatile modifier is desirable. The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer’s hardware as if it were part of the computer’s memory), and the second involves shared memory (memory used by two or more programs running simultaneously).
Most computers have a set of registers that can be accessed faster than the computer’s main memory. A good compiler will perform a kind of optimization called “redundant load and store removal.” The compiler looks for places in the code where it can either remove an instruction to load data from memory because the value is already in a register, or remove an instruction to store data to memory because the value can stay in a register until it is changed again anyway.
If a variable is a pointer to something other than normal memory, such as memory-mapped ports on a peripheral, redundant load and store optimizations might be detrimental.
If a variable point to data in shared memory, you also don’t want the compiler to perform redundant load and store optimizations. Shared memory is normally used to enable two programs to communicate with each other by having one program store data in the shared portion of memory and the other program read the same portion of memory. If the compiler optimizes away a load or store of shared memory, communication between the two programs will be affected.
24. When should the register modifier be used? Does it really help?
The register modifier hints to the compiler that the variable will be heavily used and should be kept in the CPU’s registers, if possible, so that it can be accessed faster. There are several restrictions on the use of the register modifier.
First, the variable must be of a type that can be held in the CPU’s register. This usually means a single value of a size less than or equal to the size of an integer. Some machines have registers that can hold floating-point numbers as well.
Second, because the variable might not be stored in memory, its address cannot be taken with the unary and operator. An attempt to do so is flagged as an error by the compiler. Some additional rules affect how useful the register modifier is. Because the number of registers is limited, and because some registers can hold only certain types of data (such as pointers or floating-point numbers), the number and types of register modifiers that will actually have any effect are dependent on what machine the program will run on. Any additional register modifiers are silently ignored by the compiler.
Also, in some cases, it might actually be slower to keep a variable in a register because that register then becomes unavailable for other purposes or because the variable isn’t used enough to justify the overhead of loading and storing it.
So when the register modifier should be used? The answer is never, with most modern compilers. Early C compilers did not keep any variables in registers unless directed to do so, and the register modifier was a valuable addition to the language. C compiler design has advanced to the point, however, where the compiler will usually make better decisions than the programmer about which variables should be stored in registers. In fact, many compilers actually ignore the register modifier, which is perfectly legal, because it is only a hint and not a directive.
25. When should the const modifier be used?
There are several reasons to use const pointers. First, it allows the compiler to catch errors in which code accidentally changes the value of a variable, as in
while (*str = 0) /* programmer meant to write *str != 0 */
/* some code here */
in which the = sign is a typographical error. Without the const in the declaration of str, the program would compile but not run properly.
Another reason is efficiency. The compiler might be able to make certain optimizations to the code generated if it knows that a variable will not be changed.
Any function parameter which points to data that is not modified by the function or by any function it calls should declare the pointer a pointer to const. Function parameters that are passed by value (rather than through a pointer) can be declared const if neither the function nor any function it calls modifies the data.
In practice, however, such parameters are usually declared const only if it might be more efficient for the compiler to access the data through a pointer than by copying it.
26. What is signed and unsigned variable in C language?
A numeric value may have a positive or a negative sign. In the memory, for a variable, one bit is used exclusively to maintain the sign of the data. If we don’t have sign, the sign bit also may be used for data. If the value is negative, the sign bit is 1, and if it is positive, it will be 0.