C Programming - Const - Discussion

Discussion Forum : Const - Point Out Errors (Q.No. 4)
4.
Point out the error in the program.
#include<stdio.h>
const char *fun();

int main()
{
    char *ptr = fun();
    return 0;
}
const char *fun()
{
    return "Hello";
}
Error: Lvalue required
Error: cannot convert 'const char *' to 'char *'.
No error and No output
None of above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
21 comments Page 2 of 3.

Gitanshu said:   1 decade ago
I ran the program in Dev C++ and it point outs the error given in B option.

Arj said:   1 decade ago
Pointer to a const char can be stored in a regular pointer to a char?

Please explain.

Arun Prasad said:   1 decade ago
The correct o/p is B in TC++ compiler.

Error: Cannot convert from 'const char *' to 'char *'. This occurs because fun() returns a pointer to a constant character which is being assigned to a pointer to a non-constant character.

Diana said:   1 decade ago
If the const weren't there then the ans will be C otherwise it gives error i.e ans will be B in case of Turbo C/C++ compiler.

Rahul said:   1 decade ago
@Gunjan: You are right. I also get the same error in dev.

But it will run on code::blocks.

Rahul said:   1 decade ago
@Kiran :

Here we declare the function as well as we call also in the statement
char *ptr=fun();
you can justify it by following ex:

#include<stdio.h>
const char *fun();
int main()
{
char *ptr = fun();
return 0;
}
const char *fun()
{
printf("must be call");
return "Hello";
}

Some of the compilers give error: invalid conversion from 'const char*' to 'char*' but some give the output successfully..

Gunjan said:   1 decade ago
Implementing the orignal given program in turbo C it is give error shown in option B.

Sanjee said:   1 decade ago
Inthe above program answer is b.

Because we are trying to assign const char* to char.

Kiran said:   1 decade ago
Here we have function and pointer declaration only. No calling.

Try this one, you guys may understand.

#include<stdio.h>
const char *fun()
{
return "Hello";
}
int main()
{
char *ptr=fun();
printf("%c",*ptr++);

printf("%c", *ptr++);
printf("%c", *ptr++);
printf("%c", *ptr++);
printf("%c", *ptr++);

getch();
}

Kiran said:   1 decade ago
Here we declare the function only, no calling thats why sub function doesn't execute.


Post your comments here:

Your comments will be displayed after verification.