C versus C++


A program different in C and C++: Below is a single program that compiles and runs differently in pre-ANSI C and in C++. It uses the fact that "//" on a line does not start a comment in pre-ANSI C, while of course it does in C++, and it even does in ANSI/ISO C. In each case, the comments are in orange. Thus effectively the first executable statement on the left is int x = 6/2;, while the corresponding statement on the right is interpreted as: int x = 6;

C program Same program in C++
% cat dual.c
#include <stdio.h>

int main() {
   int x = 6//* skip this */2
      ;
   printf("%i\n", x);
   return 0;
}
% cat dual.c
#include <stdio.h>

int main() {
   int x = 6//* skip this */2
      ;
   printf("%i\n", x);
   return 0;
}
% cc -o dual dual.c # ANSI/ISO C plus K&R C
% dual
6
% CC -o dual dual.c  # C++
% dual
6
% cc -o dual -Xs dual.c  # (pre-ANSI) K&R C
% dual
3


Copyright © 2011, Neal R. Wagner. Permission is granted to access, download, share, and distribute, as long as this notice remains.