How does the below program output `C89` when compiled in C89 mode and `C99` when compiled in C99 mode?

CPrintfCommentsC99C89

C Problem Overview


I've found this C program from the web:

#include <stdio.h>

int main(){
    
    printf("C%d\n",(int)(90-(-4.5//**/
    -4.5)));
    
    return 0;
}

The interesting thing with this program is that when it is compiled and run in C89 mode, it prints C89 and when it is compiled and run in C99 mode, it prints C99. But I am not able to figure out how this program works.

Can you explain how the second argument of printf works in the above program?

C Solutions


Solution 1 - C

C99 allows //-style comments, C89 does not. So, to translate:

C99:

 printf("C%d\n",(int)(90-(-4.5     /*Some  comment stuff*/
                         -4.5)));
// Outputs: 99

C89:

printf("C%d\n",(int)(90-(-4.5/      
                         -4.5)));
/* so  we get 90-1 or 89 */

Solution 2 - C

the line comment // is introduced since C99. Therefore your code is equal to this in C89

#include <stdio.h>

int main(){

    printf("C%d\n",(int)(90-(-4.5/
-4.5)));

    return 0;
}
/* 90 - (-4.5 / -4.5) = 89 */

and equal to this in C99

#include <stdio.h>

int main(){

    printf("C%d\n",(int)(90-(-4.5
-4.5)));

    return 0;
}
/* 90 - (-4.5 - 4.5) = 99*/

Solution 3 - C

Because // comments only exist in C99 and later standards, the code is equivalent to the following:

#include <stdio.h>

int main (void)
{
  int vers;

  #if   __STDC_VERSION__ >= 201112L
    vers = 99; // oops
  #elif __STDC_VERSION__ >= 199901L
    vers = 99;
  #else
    vers = 90;
  #endif

  printf("C%d", vers);

  return 0;
}

Correct code would be:

#include <stdio.h>

int main (void)
{
  int vers;

  #if   __STDC_VERSION__ >= 201112L
    vers = 11;
  #elif __STDC_VERSION__ >= 199901L
    vers = 99;
  #else
    vers = 90;
  #endif

  printf("C%d", vers);

  return 0;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpikatrixView Question on Stackoverflow
Solution 1 - CPaul RubelView Answer on Stackoverflow
Solution 2 - CikhView Answer on Stackoverflow
Solution 3 - CLundinView Answer on Stackoverflow