C89 and C++ comment: C++ is not a superset of C

In C89 comments are enclosed between /* and */. // is not standard, altought many compilers support it. However, you can force your compiler not to recognise it.
This is the key for the sequent hack: when compiled as C it prints 10, when compiled as C++, it prints 100.

#include <stdio.h>

int main(){
  int a = 100//**/10
    ;
  printf("%d\n", a);
  return 0;
}

How is that possible?

In particular expression 100//**/10 evaluates to “10”. /**/ is a comment and is not considered, so it remains 100/10 (remember that // is not a comment delimiter).

When compiling as a C++ file, everything after // is a comment, and so 100//**/10 evaluates to 100.

This does not work with C99 anymore. // comments are valid in C99.

How to force C89 mode

To force gcc to compile it as strict C89 use -pedantic -std=c89.
I chose to use the .c extension, since using .cc the compiler seems to force C++ compilation (unless you specify the language).
In fact when you compile a C++ file with gcc (ggc, not g++), it understands it is a C++ file and compiles it as a C++ file. However, you will see errors. They are not compiling errors, they are linking ones.
For example:


/usr/bin/ld: Undefined symbols:
std::basic_string<char, std::char_traits<char>, std::allocator<char> >::find(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long) const

...
operator delete[](void*)
operator delete(void*)
operator new[](unsigned long)
operator new(unsigned long)
___cxa_allocate_exception
___cxa_begin_catch
___cxa_end_catch
___cxa_rethrow

___cxa_throw
___gxx_personality_v0
restFP
saveFP
collect2: ld returned 1 exit status

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: