I am having a hard time understanding the answers to this question.
Giving the following code:
int: size, size2, j;
float: x;
array[1:30] of int: nums;
For each assignment statement below, circle can or cannot to say whether it can or cannot be fully type-checked at compile time. Assume that an array’s subscript range is considered part of its type. Assume that numeric overflow is not considered a type-error.
A. size = size2 + 1; --> Answer: CAN
B. x = size; --> Answer: CAN
C. nums[j] = 33; --> Answer: CANNOT
D. nums[3] = nums[4]; --> Answer: CAN
E. nums[j] = nums[j+1]--> Answer: CANNOT
Now, compile time errors occur when the program is being converted into machine code where run time errors occur during a program's execution. I have also read up on the following stack overflow question regarding compile vs run time errors: Runtime vs Compile time. After researching both topics, I am still confused how the following answers were derived. Any help would be much appreciated.
I believe the question asks if the type checker "can"/"cannot" catch the logic error at compile time.
The type checker knows for sure A, D are valid and B is invalid (assuming no implicit conversion), so the type checker CAN determine the validity of these three statements.
However, for C and E the validity depends on the actual value of j
(e.g. they are valid when j == 1
and invalid when j == 100
). So the type checker CANNOT determine if C and E are valid (because "an array's subscript range is considered part of its type").
Note that these answers are based on the assumption that the type checker is unable to determine / does not care about the value range of j
. Some languages like Ada and Pascal support the "range" type, so those type checkers could in principle statically check if C (requiring j
having type int range 1:30
) and E (requiring j
having type int range 1:29
) are valid.