Tuesday, 1 April 2014

Although C++ is designed to have backward compatibility with C there can be many C programs that would produce compiler error when compiled with a C++ compiler. Following are some of them :

1) In C++, it is a compiler error to call a function before it is declared. But in C, it may compile (See http://sh.st/qMeGg)

#include<stdio.h>
int main()
{
   func(); // func() is called before its declaration/definition
   return 0;
}

int func()
{
   printf("Hello");
   return 0;
}

2) In C++, it is compiler error to make a normal pointer to point a const variable, but it is allowed in C.

#include <stdio.h>
int main(void)
{
    int const j = 20;

    /* The below assignment is invalid in C++, results in error
       In C, the compiler *may* throw a warning, but casting is
       implicitly allowed */
    int *ptr = &j;  // A normal pointer points to const

    printf("*ptr: %d\n", *ptr);

    return 0;
}

3) In C, a void pointer can directly be assigned to some other pointer like int *, char *. But in C++, a void pointer must be explicitly typcasted.

#include <stdio.h>
int main()
{
    void *vptr;
    int *iptr = vptr; // In C++, it must be replaced with int *iptr = (int *)vptr;
    return 0;
}

This is something we notice when we use malloc(). Return type of malloc() is void *. In C++, we must explicitly typecast return value of malloc() to appropriate type, e.g., “int *p = (void *)malloc(sizeof(int))”. In C, typecasting is not necessary.

4) This is the worst answer among all, but still a valid answer. We can use one of the C++ specific keywords as variable names. The program won’t compile in C++, but would compiler in C.

#include <stdio.h>
int main(void)
{
    int new = 5;  // new is a keyword in C++, but not in C
    printf("%d", new);
}

Similarly, we can use other keywords like delete, explicit, class, .. etc.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
byteKoding

byteKoding

byteKoding.com is started with an intention to provide every updates related to technology and programming. It is specially for helping people in developing software projects in different programming languages like C/C++, Java, C#.Net, ASP.Net etc. The details that we share here can be very much useful in creating your software a great success.

0 comments