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 1 of 3.

Ankit said:   5 years ago
The answer must be option B.
(2)

Ritesh_iiita said:   1 decade ago
@Arun prasad:

O/P in gcc compiler is also b its is throwing error i.e invalid conversion from const char to char. here is the code and output:

#include<stdio.h>
const char *fun();

int main()
{
char *ptr =fun();
return 0;
}
const char *fun()
{
return "Hello";
}

o/p:7 INDIABIXTEST6_18.C [Error] invalid conversion from 'const char*' to 'char*' [-fpermissive]

Kavya said:   7 years ago
char *ptr is not a pointer to the function, then how can it point to fun()?

Akash said:   8 years ago
Yes, you are right @Lakshmi.

Because pointer contains constant string only.

So, the fun() returns a constant string so to store constant string pointer must be required.

Thank you.

Pradeep said:   9 years ago
@All. Refer this code.

#include<stdio.h>
const char *fun();

int main()
{
char *ptr = (char*)fun();
//printf("%p %s\n",&ptr,ptr);
puts(ptr);
return 0;
}
const char *fun()
{
return "Hello";
}

Muhammad Najmudheen said:   9 years ago
/*Actually the code will work fine if we declare the pointer in main function as*/

const char *ptr=fun();

/*It is because here the function returns a constant character pointer value. so it should be received like that only*/

return "hello";

/*This statement will store the string in memory and will return the base address of the string. It will work fine since the function is declared as a function which will return a constant character pointer value and it is received by a constant character pointer in main function.*/

Amit Duhan said:   1 decade ago
6 21 [Error] invalid conversion from 'const char*' to 'char*' [-f permissive].

Compiler DevC++.

Srujan said:   1 decade ago
Here the string "hello" is local to that function and when it returns it goes out of scope and returns nothing.

Lakshmi said:   1 decade ago
I hope there is no problem with assigning char* to const char*. So no error.

As there is printf statement in the program there is no output.
So option C is correct.

\\Check with the following program. It will help you friends.

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

Indi said:   1 decade ago
In gcc if you print the pointer there is no error with that code.


Post your comments here:

Your comments will be displayed after verification.