Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement requires extra semicolon in Visual Studio 2013

I'm compiling some C code in Visual C++ 2013 (it has to be written in C).

void drawDebugLines(vec2f pos, DebugControls *controls, vec2f dydx, vec2f p)
{
    static float lineSize = 0.05f;
    if (!controls->normalFlag && !controls->tangentFlag)
    {
        return;
    }
    vec3f nColor = cVec3f(1, 1, 0);
    ...

As-is this code will compile and run just fine.

If I take out those curly braces, I get the following compile error:

error C2275: 'vec3f' : illegal use of this type as an expression

Edit: This error occurs for the statement vec3f nColor

However if I put in a grand total of two semicolons after the return statement (and no braces), the code will also compile and run just fine.

This only happens in Visual C++, gcc will compile this code without requiring the braces or extra semicolon.

My question is why does Visual C++ do this? I'm happy to accept the answer "Visual Studio's C compiler is s***" but why/how is it s***?

I should point out that in my header files I have everything wrapped inside

#if __cplusplus
extern "C" {
#endif
...
#if __cplusplus
}
#endif

I'm not sure if that's relevant but I thought I should mention it just in case.

Edit: code you can just throw into a file and witness the magic:

Extra edit: the extension for the filename must be .c, if it's .cpp then the code compiles.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct vec3f vec3f;

struct vec3f
{
    float x, y, z;
};

vec3f cVec3f(float x, float y, float z)
{
    vec3f v;
    v.x = x;
    v.y = y;
    v.z = z;
    return v;
}

void drawDebugLines(vec3f pos, bool debug)
{
    if (!debug)
        return;;

    vec3f nColor = cVec3f(1, 1, 0);

    printf("nColor: %f %f %f\n", nColor.x, nColor.y, nColor.z);
}


int main(int argc, char **argv)
{
    vec3f pos = cVec3f(0, 0, 0);
    drawDebugLines(pos, true);

    return EXIT_SUCCESS;
}

Take out the extra semicolon and watch it break. If it doesn't break for you and it's just my version of Visual C++ that fails then honestly that would make the most sense to me.

like image 779
Blarglenarf Avatar asked Mar 27 '15 14:03

Blarglenarf


1 Answers

This was a bug in the C compiler in Visual Studio 2013. It was fixed in Visual Studio 2013 Update 2.

like image 81
James McNellis Avatar answered Sep 28 '22 00:09

James McNellis