1,624 views
10 votes
10 votes

Consider the following usage of variable a where b is an appropriate pointer variable.

int * b = &a;

Which of the following declarations is invalid for a?

  1. auto int a;
  2. register int a;
  3. static int a;
  4. const int a;
  1. 1 and 2
  2. 4 only
  3. 2 only
  4. 2 and 4

3 Answers

Best answer
7 votes
7 votes

When a variable is stored in a registor, then it can be stored inside registor and not inside memory and accessing address of register is invalid .

hence, option C is correct .

But if pointer is stored inside register and acccesses a variable in memory, then compiler has no problem .

selected by
0 votes
0 votes
b is a pointer type variable . it will hold the address of a . if we store a into a register then it means by 'b'' we want to know address of register finally. that is not possible because register have not a specific address.

so option (c) is correct
0 votes
0 votes

Let's see these declarations one-by-one.

"Auto int"

In C, auto means "not static". Usual local variables are not static by defualt.

There's literally no difference between a local

int a;

and

auto int a;

"Register int"

A programmer uses the "register" keyword for a variable to hint the compiler that this variable is going to be frequently used, and to optimise performance the compiler should keep it in the register.

However, it is perfectly legal for the compiler to flat-out ignore this request, and depend on its judgement on what to put in the registers.

Also, you can't take the address of a register int. (Statement 2)

Hence, using register keyword is unadvisable, as the compiler can ignore it, and you'd also lose the & operator.


"Static int"

We all know what this is. A static variable is stored in the Runtime environment right at the beginning of the process's execution. Static ints can only be initialised once, and if not initialised by the programmer, they implicitly get initialised to 0 by the compiler.

Note: Global variables too get initialised to 0 if not explicitly initialised by the programmer.


"Const int"

The "const" keyword would keep the value invariable / constant. In other words, it would implement read-only behaviour.




 

Hence, only for "register int a;" the given declaration would cause a problem, as it's illegal to fetch its address. Option C

Answer:

Related questions

3 votes
3 votes
2 answers
2
8 votes
8 votes
2 answers
3
1 votes
1 votes
3 answers
4