简体   繁体   English

子程序中的C Hello World程序

[英]C Hello World Program in a subroutine

#include <stdio.h>
#include <stdlib.h>

void message(char m)
{
print("Hello\n");
}

int main()
{
message(m);    
}

Error message when I try to compile 我尝试编译时出现错误信息

danielc@Ubuntu11:$ gcc Messagef.c -o Messagef
    Messagef.c: In function ‘main’:
    Messagef.c:11:9: error: ‘m’ undeclared (first use in this function)
    Messagef.c:11:9: note: each undeclared identifier is reported only once for each function it appears in

I know that am doing a 'silly' mistake but I just see where am going wrong 我知道这是一个“愚蠢”的错误,但我只是想知道哪里出了问题

Your function takes a char parameter but never uses it. 您的函数采用char参数,但从不使用它。 The simplest fix is to remove the unused parameter: 最简单的解决方法是删除未使用的参数:

#include <stdio.h>

void message()
{
    printf("Hello\n");
}

int main()
{
    message();    
    return 0;
}

Alternatively, change your method to use the parameter, and pass in a character as an argument: 或者,更改您的方法以使用参数,并传入一个字符作为参数:

#include <stdio.h>

void message(char m)
{
    printf("Hello%c\n", m);
}

int main()
{
    message('!');    
    return 0;
}

See it working online: ideone 看到它在线上工作: ideone

  1. Declare m in your main (char m = '?';) 在您的主声明中声明m(char m ='?';)
  2. Try "printf" instead of "print" 尝试使用“ printf”而不是“ print”

the variable "m" your passing to the message function has not been defined before its passed. 传递给消息函数的变量“ m”在传递之前尚未定义。

define the m variable above message() or pass a char literal to the function 在message()上方定义m变量或将char文字传递给函数

Your function expects a char and you are passing m without declaring it. 您的函数需要一个char,并且您正在传递m而不声明它。 You need to declare m first like this: 您需要先这样声明m

char m = 'a';

And then call the function. 然后调用该函数。 BTW, you are not doing anything with this variable so it is redundant anyway. 顺便说一句,您对此变量没有做任何事情,因此无论如何它都是多余的。

Pick up a book of C language and start following that. 拿起一本C语言的书,然后开始学习。

alternately u can initialise m with Hello message. 或者,您可以使用Hello消息初始化m。 pass the pointer to message to function and then print in message function, somewhat like this: 将指向消息的指针传递给函数,然后在消息函数中打印,如下所示:

void message(char *msg)
{
printf("%s", msg);
}

int main()
{
char *m = "Hello";
message(m);
return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM