Search code examples
c++cvisual-studiomingwfunction-definition

Visual Studio C/C++ extension shows error message even if the code is correct


My Visual Studio compiler is showing me error messages even when the code is correct.

Even on a simple code like,

 #include<stdio.h>

int main(){
    int add(firstNumber, secondNumber){
        int result=firstNumber+secondNumber;
        return result;
    }
    int out=add(10,30);
    printf("%d", out);
    return 0;
}

It's showing the massage,

expected a ';', line 4

and

identifier "out" is undefined, line 9

The code runs well. But it's frustrating seeing those red lines and the error messages on my code.

Note: I'm using MinGW as a C path


Solution

  • Neither C nor C++ Standard allows nested function definitions as in this program

     #include<stdio.h>
    
    int main(){
        int add(firstNumber, secondNumber){
            int result=firstNumber+secondNumber;
            return result;
        }
        int out=add(10,30);
        printf("%d", out);
        return 0;
    }
    

    where the function add is defined within the function main.

    Moreover the identifiers firstNumber and secondNumber in the parameter list do not have type specifiers.

    You have to move the function definition outside main. For example

    #include<stdio.h>
    
    int add( int firstNumber, int secondNumber )
    {
        int result = firstNumber + secondNumber;
        return result;
    }
    
    int main( void ){
        int out=add(10,30);
        printf("%d", out);
        return 0;
    }
    

    In C++ you could use a lambda expression instead of the function add. For example

    #include <cstdio>
    
    int main()
    {
        auto add = []( int firstNumber, int secondNumber )
        {
            return firstNumber + secondNumber;
        };
    
        int out = add(10,30);
    
        printf( "%d\n", out );
    
        return 0;
    }