main()在C和C++中定义函数的正确(最有效)方法是什么- int main()或void main()- 为什么?如果int main()那么return 1或return 0?
这个问题有很多重复,包括:
main()函数的有效签名是什么?main()函数void main()和int main()?main()在C++中的签名main()? - 对于C++,确实有一个非常好的答案.main()C语言中的函数样式main()C中的方法类型int main()vs void main()在C中有关:
这是重现的最小C程序:
#include <alsa/asoundlib.h>
#include <sys/time.h>
int main( void )
{
}
Run Code Online (Sandbox Code Playgroud)
这将编译gcc -c -o timealsa.o timealsa.c,但如果您包含该-std=c99开关,则会出现重新定义错误:
In file included from /usr/include/sys/time.h:28:0,
from timealsa.c:3:
/usr/include/bits/time.h:30:8: error: redefinition of ‘struct timeval’
struct timeval
^
In file included from /usr/include/alsa/asoundlib.h:49:0,
from timealsa.c:2:
/usr/include/alsa/global.h:138:8: note: originally defined here
struct timeval {
^
Run Code Online (Sandbox Code Playgroud)
如何在仍然使用时解决此冲突-std=c99?
我正在学习编程C.你能解释一下这里为什么没有打印出来吗 提前致谢.
#include <stdio.h>
int main (void)
{
char a[]="abcde";
printf ("%s", a);
}
Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
#include <iostream>
using namespace std;
int testReturn()
{
// no return
}
int main()
{
cout << "!!!Hello World!!!" << testReturn() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器警告:..\src\test.cpp:15:1: warning: no return statement in function returning non-void [-Wreturn-type].所以在我的编译器中,输出是1:
!!!Hello World!!!1
Run Code Online (Sandbox Code Playgroud)
没有将return语句指定为未指定的行为吗?还是总是不为零?我将非常感谢所有的帮助.
在c中使用return(0)的用途是什么,因为我已经编写了一些可以在不使用return(0)的情况下正常运行的程序,请以一种非常简单的方式告诉我,我是c的初学者,如果答案很复杂,则可能让我更加困惑:(
先谢谢了 :)
#include <stdio.h>
#include <stdlib.h>
int main()
{
float km, meter, feet, inch, cm;
printf("Enter the distance(must be in km: \n");
scanf("%f", &km);
cm = 100000*km;
inch = 39370.1*km;
meter = 1000*km;
printf("The distance between the cities in cm is %f \n", cm);
printf("The distance between the cities in inches is %f \n", inch);
printf("The distance between the cities in meters is %f \n", meter);
}
Run Code Online (Sandbox Code Playgroud) 为什么C中的main()函数可以正确终止,即使不使用exit或return?
例如:
#include<stdio.h>
int sum(int a,int b)
{
return (a + b);
}
int main()
{
int a=10;
int b=5;
int ans;
ans=sum(a,b);
printf("sum is %d",ans);
}
Run Code Online (Sandbox Code Playgroud) 我不确定为什么下面的代码不起作用.
我尝试用gcc编译它gcc -Wall -o test test.c,它给出了警告信息:控制到达非void函数的结束.
但是我找不到错误所以我试图编译它忽略警告消息,并在使用./test 1234321编译后使用它来测试程序gcc -o test ispalidrome.c
但不是返回0(它应该由我理解,因为它没有触发任何if语句返回1),它返回一个随机值,46,52,84等.
该程序背后的主要逻辑完全按照要求,我只是不知道为什么它没有正确退出.
#include <stdio.h>
int main(int argc, char **argv){
if (argc != 2){
fprintf(stderr, "Usage: %s \"string\"", argv[0]);
return 1;
}
else{
int i = 0;
while( '\0' != argv[1][i] ) i++;
char *start=argv[1];
char *end=&start[i-1];
while (start<end){
if (*start != *end){
break;
return 1;
}
printf("%c is the same as %c\n",*start, *end);
start =start+1;
end=end-1;
}
}
}
Run Code Online (Sandbox Code Playgroud) c ×5
c++ ×2
alsa ×1
c99 ×1
function ×1
gcc ×1
pointers ×1
printf ×1
return ×1
return-type ×1
return-value ×1
while-loop ×1
x86 ×1