📜  门| GATE-CS-2001 |问题7(1)

📅  最后修改于: 2023-12-03 15:12:39.805000             🧑  作者: Mango

GATE-CS-2001 Question 7

This is a question from the Computer Science section of the Graduate Aptitude Test in Engineering (GATE) for the year 2001.

Problem Statement

Consider the following C program:

#include <stdio.h>
void main()
{
   int x = 10;
   int *ptr;
   ptr = &x;
   *ptr = (*ptr)++ + 5;
   printf("%d",x);
}

What will be the output of the program?

A. 10
B. 15
C. 16
D. 20

Solution

The program initializes an integer variable x to 10 and declares a pointer variable ptr of type int*. It then assigns the address of x to ptr using the address-of operator &.

The next line increments the pointer's value and then adds 5 to it. The increment operator ++ has higher precedence than the dereference operator *, so it increments the value pointed to by ptr and returns the original value. The addition operator + then adds 5 to this original value and sets the result back at the address pointed to by ptr.

Finally, the program prints the value of x. Since x was updated to 15 within the program, the output of the program will be 15. Therefore, the answer is B. 15.

## Solution

The program initializes an integer variable `x` to 10 and declares a pointer variable `ptr` of type `int*`. It then assigns the address of `x` to `ptr` using the address-of operator `&`.

The next line increments the pointer's value and then adds 5 to it. The increment operator `++` has higher precedence than the dereference operator `*`, so it increments the value pointed to by `ptr` and returns the original value. The addition operator `+` then adds 5 to this original value and sets the result back at the address pointed to by `ptr`.

Finally, the program prints the value of `x`. Since `x` was updated to 15 within the program, the output of the program will be 15. Therefore, the answer is **B. 15**.