This question already has answers here:
C function defined as int but having no return statement in the body still compiles
(7 answers)
Closed 8 years ago.
#include <stdio.h>
int func()
{
}
int main(void)
{
printf("%d\n",func());
return 0;
}
the function "func()" is of "int" return type but is not returning anything. When the function is called in the print function, why is it giving an output 0? And why does it compile successfully although the function definition does not agree to the function code?
If you enable warnings you will see a diagnostic. Traditionally, C implicitly allowed all functions to return int. The behavior of the return value is undefined, so it is not guaranteed to be 0. The behavior could change on different compilers or on different platforms or with different optimization flags or even just by adding or removing other unrelated code. The reason you are probably seeing 0 is because you are running unoptimized and whatever previous value happens to be in the register or stack position is 0. This is pure chance, and relying on the behavior will ultimately result in bugs in your code.
Related
This question already has answers here:
Why does the main function work with no return value?
(2 answers)
What should main() return in C and C++?
(19 answers)
Closed 2 years ago.
Read all this to understand my problem: In my collage test there was a question like this:
What is the error in this code:
#include<stdio.h>
int main(){
printf("Hello World");
}
Answer of above code: compiling Error
But This is what I got when I try it practically:
As per books we have to return 0; when we use int main()
can any one give perfect or understandable Explanation.
Absence of return statement will never raise compiling error. Especially for main function, that handles differently. If it has type int but have doesn't return anything, a program acts like main returns 0.
Theoretically, it can be compiler-dependent, but in you case, it's likely an error in test.
You should return 0 but not doing that is not a compiling error.
UPD: as #EricPostpischil mentioned in comments, compilers don't raise an error because they have a mode set by default that allows to compile non-standard code, so question in your test is incomplete. It has to specify compiler you are using etc.
This question already has answers here:
Why cast unused return values to void?
(10 answers)
Closed 5 years ago.
From Programming Language Pragmatics, by Scott:
If the programmer wishes to call a subroutine that does return a
value, but the value is not needed in this particular case (all that
matters is the side effect[s]), then the return value in C can be
discarded by “casting” it to void:
foo_index = insert_in_symbol_table(foo);
...
(void) insert_in_symbol_table(bar);
Can I just call such a subroutine which returns a value as if it returned void?
insert_in_symbol_table(bar);
What syntax or semantics rules do I violate?
Thanks.
You aren't required to put the cast to void in. For example, the printf function returns a value (how many characters were written), but it's rare to see someone catch the return value or cast it to void.
A void cast is often a good idea if you're calling a function specifically for the side effects in a way that's unusual or counterintuitive and you want to explicitly signal to other people reading the code that yes, you know you're ignoring the return value, and that yes, that was intentional.
You don't violate any rules. The reason why you would want to explicitly do that cast is to let the compiler or a static code analyzer know that you're ignoring the return value on purpose else they might complain about a discarded return value. The reason that code analyzers or a compiler might warn you about this is because usually when a function returns something it's considered information that should be checked/processed.
I don't find the void casting very useful.
As far as I understand, it's just as good as a comment, and it won't silence
warnings from __attribute__((__warn_unused_result__)) functions (a gcc/clang extension).
I've been using an explicit ignore macro that does silence these (or to simply say I'm ignoring a return value).
/*Ignore macro ( NS == your libs namespace) */
#define NS_ign(Expr) do{__attribute__((__unused__)) __typeof(Expr) NS_ign = Expr; }while(0)
/*example usage*/
#include <stdio.h>
__attribute__((__warn_unused_result__))
int Puts(char const *X) { return puts(X); }
int main()
{
//puts returns an int -- no harm done if you silently ignore it
puts("hello world");
/*(void)Puts("hello world");*/ //(void) cast doesn't silence WUR
NS_ign(Puts("hello world")); //this does
}
This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 6 years ago.
I just wanna know what happens internally when we return a value. If we dont return a value what are the consequences?
#include <stdio.h>
int main() {
printf("Hello world");
return 0; //what is use of this?
}
it can be evaluated by the system to determine if a program failed to run (and why it failed)
I think perhaps you have two questions:
Why does main() return int and not void?
This question has already been answered in many forms. Basically: for the program that called it (a shell, perhaps, or your IDE), so that it can distinguish between success and various modes of failure.
What happens if you forget to return a value from main()?
In the first standardized version of C (C89) there was nothing special about main() in this respect. If you forgot to return a value, the behavior was undefined. In practice, most compilers will act as if you had put return 0;.
Since C99, if you do not return a value from main() explicitly, then main() is defined to return 0. main() is special in this way; other functions do not implicitly return anything.
As Weather Vane said in the comments, your program can't not return a value (on platforms where "return value" is a meaningful concept). On Linux, execve() and similar functions return an int that is the return value of the program. If a program were ill-behaved and did not intend to return a value, the return value would probably just be some arbitrary value (but it's possible that on another platform such a program would crash).
Not every program or function returns a value. In c, we use return 0 in order to give back control to the operating system when the program is finished running and also to make sure that the program runs smoothly.
Hope that helps. Cheers
This question already has answers here:
Turbo C++: Why does printf print expected values, when no variables are passed to it?
(5 answers)
Closed 9 years ago.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=11;
clrscr();
printf("%d");
getch();
}
Output=11
How the output is 11 even I am not mentioned the variable name in the printf function.
The 11 is on the stack because of the b variable, and your printf() function is looking on the stack for a value on the stack because that's where variables get passed.
If you add a c=47, you'll probably get 47. But this is undefined behavior.
This is called "undefined behavior", which means that program can do just about anything.
What is actually happening in this case is that both variables and function parameters are put on the stack. Since you aren't passing the parameter that printf is expecting, it ends up pulling something else off the stack, which is your b variable.
But because it is undefined behavior, if you had a different compiler, a different CPU, or even different compile options, such as a higher optimization level, you could get very different results.
This question already has answers here:
Why do C standards allow you not to return a value from a function?
(5 answers)
Closed 4 years ago.
I'm implementing some basic data structures in C and I found out that if I omit the return type from a function and call that function the compiler doesn't generate an error. I compiled with cc file.c and didn't use -Wall (so I missed the warning) but in other programming languages this is a serious error and the program won't compile.
Per Graham Borland's request, here's a simple example:
int test()
{
printf("Hi!");
}
int main()
{
test();
}
C is an old language and at the time it was introduced, returning integers was common enough to be the default return type of a function. People later started realizing that with more complicated return types, it was best to specify int to be sure you are not forgetting the return type, but in order to maintain backwards compatibility with old code, C could not remove this default behavior. Instead most compilers issue warnings.
If the function reaches the end without a return statement an undefined value is returned except in the main function, 0 is returned. This has the same reason as above.
/* implicit declaration of printf as: int printf(int); */
/* implicit int type */
main()
{
printf("hello, world\n");
} /* implicit return 0; */
It's because in C, any variable / function is implicitly int.
This is the same reason that you can use register instead of register int, or unsigned instead of unsigned int, auto instead of auto int, and static instead of static int. I personally always explicitly qualify my variables with int, but whether you do or not is your option.
The return type of a function is optional and is considered "int" if not specified.
I haven't seen the why addressed well in any of the answers so far. In C, it's perfectly legal for a function with a non-void return type to end without a return statement/value, as long as the caller does not attempt to use the return value. For instance (slightly nontrivial example):
#include <stdio.h>
int foo(int want_result)
{
puts("hello");
if (want_result) return 42;
}
int main()
{
foo(0);
printf("%d\n", foo(1));
}
This example is somewhat contrived, but it could actually become meaningful if the return type is a huge structure that would take non-trivial time to return.
The function will not return 0 as the Matt's answer says.
In fact, printf returns a value: the number of characters printed. In your case, printf, which is the last expression in your test function, will return 3. Thus the function test will return 3.