I wrote the following code to play with a specific C11 idiom of anonymous structs described in the book "21st Century C".
#include <stdio.h>
#include <math.h>
typedef struct Price {
double close;
double high;
double low;
} Price;
typedef struct OLHC {
union { //union allows the dual benefits of the seamless anon. struct and code-reuse
struct Price; //an anonymous struct but not explicitly re-defined
Price p;
};
double open;
} OHLC;
double range(Price p){ //behaviour defined for struct Price
return(p.high - p.low);
}
double travelRange(OHLC p){ //re-uses behaviour defined for struct Price
return (fabs(p.open - p.low) + range(p.p) + fabs(p.high - p.close));
}
int main(){
OHLC msft={.close=33.4, //seamless access to members
.open=32.1,
.high=35.5,
.low=30.23};
printf("Today's travel Range for MSFT was %f\n",travelRange(msft));
}
I can get it to compile without warnings with either gcc48 or gcc49 as follows:
gcc-4.9 -std=c11 -fms-extensions -lm -o c11 c11.c
I can also get it to compile and run on my OS X mavericks macbook with one warning:
cc -std=c11 -fms-extensions -lm -o c11 c11.c
The warning is:
c11.c:19:5: warning: anonymous structs are a Microsoft extension[-Wmicrosoft]
Is there any version of gcc or clang which will compile this file with just the std=c11 flag without warnings. Are anonymous structs/unions part of C11 standard and just not implemented yet or are they as used above not conformant?
EDIT: Just to clarify the code above is designed to allow the reuse of code written for the base structure but at the same time get the benefits of the seamless access to all members of the derived structure containing the original structure anonymously. This is accomplished with the union of an anonymous struct and its corresponding named type. Too bad this is not conforming as I thought it was a really nice little idiom.