Following C standards, your program is not wrong.
You've used nested functions and that's supported in C. The reason to why your program worked just fine when compiled using gcc
and not in VS Code is that
Nested functions are supported as an extension in GNU C, but are not supported by GNU C++
according to this(which was also pointed out by @luther in his answer).
VS Code's C/C++ extension uses the g++
command to compile C and C++ programs (yes, you can use both gcc
and g++
to compile .c and .cpp files). g++
will compile .c and .cpp files, but will treat them as C++ files. So, now it's clear why your program does not work when compiled and run in VS Code.
Check this to look at VS Code's C/C++ extension and this to know the difference between gcc
and g++
.
If you really want to have your program compile and run in VS Code then you can choose to do one of these 2:
- You can place the the minDist() before the main() function in your code like this:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
printf("\nThe Minimum Distance between %d and %d is %d.\n",x, y,minDist(a,n,x,y));
free(a);
return 0;
}
- You may declare the function before the
main()
function and have the function's body after the main()
function. Like this:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int minDist(int arr[], int n, int x, int y); // declaration of the minDist() function
int main()
{
int n, x, y, i, j;
printf("How many numbers do you want to enter? ");
scanf("%d",&n);
int *a=(int*)malloc(n*sizeof(int));
printf("Enter the numbers: ");
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
printf("Enter the value of the two distance x and y: ");
scanf("%d %d",&x,&y);
printf("\nThe Minimum Distance between %d and %d is %d.\n",x, y,minDist(a,n,x,y));
free(a);
return 0;
}
int minDist(int arr[], int n, int x, int y)
{
int i, j;
int min_dist = INT_MAX;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if ((x == arr[i] && y == arr[j]
|| y == arr[i] && x == arr[j])
&& min_dist > abs(i - j)) {
min_dist = abs(i - j);
}
}
}
if (min_dist > n) {
return -1;
}
return min_dist;
}
Edit: Many thanks to Erik Postpischil for pointing out that I have not completely answered the question.