Is the below declaration valid in C?
#include<stdio.h> main() { int arr[2] = {1,2}; printf("%d", arr[arr[0]]); }
--------------------------------------------------
There are several programs and code snippets we see everywhere where there is unusual usage. When we say unusual usage we mean differing from the traditional way of implementing. For example, if we see the above implementation, the member of array is accessed using arr[arr[0]].
arr[0] or arr[1] is the normal way of accessing the elements of array. However, in arr[arr[0]], arr[0] is first accessed and that is used as index to access next element which syntax wise doesn't look wrong. So, in the above code, arr[0] = 1 and then arr[arr[0]] = arr[1] = 2.
Few points to remember while we analyze such snippets:
- Check the syntax first, if it looks fine then analyze further
- Check if the code is accessing out of bound values or undeclared variables.
0 Comments