Home > Enterprise >  Suppose we declare an array as: int a[10]; then what is a?
Suppose we declare an array as: int a[10]; then what is a?

Time:06-28

Basically this question appeared in a college test of mine (I know we shouldn't ask test questions here but this is a theoretical test question) which was like:

Question

Answer given by the professor's team is (D)None of these. Please help.

CodePudding user response:

Arrays are weird.

Given the declaration

int a[10];

you get the following in memory (? represents an indeterminate value, assuming this is an auto array):

    ––– 
a: | ? | a[0]
    ––– 
   | ? | a[1]
    ––– 
    ...
    ––– 
   | ? | a[9]
    –—– 

There is no object a separate from the array elements themselves. You cannot assign a new value to a by itself; the compiler will reject code like

a = some_other_array_name;

Under most circumstances the expression a will "decay" to a pointer to the first element (equivalent to &a[0]).

So, is a a variable or not? The problem is that the term "variable" is kind of sloppy with respect to C.

In C, you have objects (regions of memory that can potentially store values) and lvalues (expressions through which objects can be read or modified). The expression a[i] is an lvalue - it can be used to assign a new value to an object (the ith element of the array):

a[i] = 42;

However, there are things called "non-modifiable" lvalues that designate objects but cannot be the target of an assignment. Array expressions like a are non-modifiable lvalues.

Since the expression a cannot be the target of an assignment, I would say D is a viable answer. But since a designates a region of storage that can be modified (just not through the expression a itself), A is also a viable answer.

I suspect your professor is using "variable" to mean "can be the target of an assignment", which is why they consider D to be the correct answer.

CodePudding user response:

Answer:

  1. a - is a variable.
  2. a decays to a pointer to an integer when used in expressions, but it is not a pointer.
  • Related