C program that won't compile in C++

C++ is largely based on C, but it enforces stricter type checking and syntax rules. While most C programs compile in C++, some valid C code will not compile in C++ due to these stricter rules. Understanding these differences helps in writing portable code.

Syntax

There is no specific syntax for this concept, but rather a collection of C language features that C++ treats differently or rejects entirely.

Example 1: Function Declaration Requirements

In C, functions can be called before declaration (with implicit declaration), but C++ requires explicit declaration −

#include <stdio.h>

int main() {
    myFunction(); /* Function called before declaration */
    return 0;
}

int myFunction() {
    printf("Hello World");
    return 0;
}
Hello World

C++ Error: 'myFunction' was not declared in this scope

Example 2: Const Pointer Assignment

C allows assigning const variable addresses to non-const pointers, but C++ prohibits this −

#include <stdio.h>

int main() {
    const int x = 10;
    int *ptr;
    ptr = &x; /* Assigning const address to non-const pointer */
    printf("The value of x: %d", *ptr);
    return 0;
}
The value of x: 10

C++ Error: invalid conversion from 'const int*' to 'int*'

Example 3: Void Pointer Assignment

C allows implicit conversion from void pointer to other pointer types, C++ requires explicit casting −

#include <stdio.h>

int main() {
    void *x;
    int *ptr = x; /* Implicit conversion from void* to int* */
    printf("Done");
    return 0;
}
Done

C++ Error: invalid conversion from 'void*' to 'int*'

Example 4: Uninitialized Constants

C allows declaring const variables without initialization, C++ requires initialization −

#include <stdio.h>

int main() {
    const int x; /* Uninitialized const variable */
    printf("x: %d", x);
    return 0;
}
x: 0

C++ Error: uninitialized const 'x'

Example 5: Using C++ Keywords as Variables

C allows using C++ keywords like 'new' as variable names, but C++ treats them as reserved keywords −

#include <stdio.h>

int main() {
    int new = 10; /* 'new' is a keyword in C++ */
    printf("new: %d", new);
    return 0;
}
new: 10

C++ Error: expected unqualified-id before 'new'

Key Differences Summary

Feature C Behavior C++ Behavior
Function Declaration Implicit declaration allowed Explicit declaration required
Const Pointer Assignment Allowed Not allowed
Void Pointer Conversion Implicit conversion Explicit casting required
Const Initialization Optional Mandatory
C++ Keywords as Variables Allowed Not allowed

Conclusion

C++ enforces stricter type safety and syntax rules compared to C. Understanding these differences is crucial when migrating C code to C++ or writing code that needs to compile in both languages.

Updated on: 2026-03-15T10:43:27+05:30

572 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements