Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What C program behaves differently in run-time when compiled with C89 and C99?

I found the following snippet (I think in Wikipedia) that creates a different run-time when C++ comments are recognized than when not:

int a = 4 //* This is a comment, but where does it end? */ 2
  ;

But until now that's been the only one (variants excluded).

I'm not interested in differentiating using __STDC__ and the like, and not in programs that C89 will not compile.

Are there other programs/snippets producing a different run-time with C89 than C99?

like image 779
Johan Bezem Avatar asked Nov 17 '11 05:11

Johan Bezem


People also ask

What is the difference between C89 and C99?

In C89, the results of / and % operators for a negative operand can be rounded either up or down. The sign of i % j for negative i or j depends on the implementation. In C99, the result is always truncated toward zero and the sign of i % j is the sign of i. In C89, declarations must precede statements within a block.

What is the difference between C99 and C11?

C11 looked to address the issues of C99 and to more closely match the C++ standard, C++11. It changes some C99 features required to optional. Some of the features include variable length arrays and complex numbers. This makes it easier for compiler vendors to meet C11's required function set.

Does all c code work in C++?

Even though most C++ compilers do not have different linkage for C and C++ data objects, you should declare C data objects to have C linkage in C++ code. With the exception of the pointer-to-function type, types do not have C or C++ linkage.

Does C++ compiler compile C?

If the compiler uses C++ to compile C code you might have issues if in the C code you use words that are reserved in C++. Will compile fine with a C compiler (or C++ compiler in C mode), but will not compile with a C++ compiler.


2 Answers

This program will print 0.000000 on a conforming C89 implementation and 1.000000 on a conforming C99 implementation:

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

int main()
{
    double d = strtod("0x1", NULL);
    printf("%f\n", d);
    return 0;
}
like image 129
caf Avatar answered Sep 19 '22 09:09

caf


Two examples:

  • C99 has -3/2 as Defined Behaviour (namely, to truncate to zero).

  • C99 has -1<<1 as Undefined Behaviour (but not C89).

Also, in the past I've run into problems with 64-bit enums, such as enum {mask = 1ULL << 32}, but I don't recall if the compiler was silent, or just quietly did the wrong thing.

like image 39
Joseph Quinsey Avatar answered Sep 21 '22 09:09

Joseph Quinsey