473,605 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

First program in C - what is going on with function returns?

Hi,

I have just written a simple program to get me started in C that
calculates the number of days since your birthdate.
One thing that confuses me about the program (even though it works) is
how global variables and function returns work...

For example, I have a global array "char datestring[80];" which is
defined in the function speakdate. speakdate just converts a set of
integers (date variables) to a string.

The main program then does:
"printf ("The current date is:
%s\n\n",speakda te(cdate,cmonth ,cyear));"

And correctly prints the value of datestring.
What I don't get is why this works since I haven't explicitly told
speakdate to return datestring.
I figured by default it would return nothing at all.

Full code below. By the way any other tips on my code would be welcomed
and appreciated!

cheers,

Ben C

Expand|Select|Wrap|Line Numbers
  1. char datestring[80];
  2. /* dim is 'days in month'*/
  3. int dim;
  4.  
  5. speakdate(int d, int m, int y)
  6. {
  7.  
  8. char stdate[5],stmonth[10],styear[5];
  9.  
  10. sprintf( stdate, "%d", d);
  11. sprintf( styear, "%d", y);
  12.  
  13. switch (d) {
  14. case 1 :
  15. case 21 :
  16. case 31 : strcat(stdate,"st ");
  17. /*printf("The date is %s\n",stdate);*/
  18. break;
  19. case 2 :
  20. case 22 : strcat(stdate,"nd ");
  21. /*printf("The date is %s\n",stdate);*/
  22. break;
  23. case 3 :
  24. case 23 : strcat(stdate,"rd ");
  25. /*printf("The date is %s\n",stdate);*/
  26. break;
  27. case 4 :
  28. case 5 :
  29. case 6 :
  30. case 7 :
  31. case 8 :
  32. case 9 :
  33. case 10 :
  34. case 11 :
  35. case 12 :
  36. case 13 :
  37. case 14 :
  38. case 15 :
  39. case 16 :
  40. case 17 :
  41. case 18 :
  42. case 19 :
  43. case 24 :
  44. case 25 :
  45. case 26 :
  46. case 27 :
  47. case 28 :
  48. case 29 :
  49. case 30 : strcat(stdate,"th ");
  50. /*printf("The date is %s\n",stdate);*/
  51. break;
  52. default : strcat(stdate,"Invalid ");
  53. /*printf("The date is %s\n",stdate);*/
  54. break;
  55. }
  56.  
  57. switch (m) {
  58. case 1 : strcpy(stmonth,"January");
  59. /*printf("The month is %s\n",stmonth);*/
  60. break;
  61. case 2 : strcpy(stmonth,"February");
  62. /*printf("The month is %s\n",stmonth);*/
  63. break;
  64. case 3 : strcpy(stmonth,"March");
  65. /*printf("The month is %s\n",stmonth);*/
  66. break;
  67. case 4 : strcpy(stmonth,"April");
  68. /*printf("The month is %s\n",stmonth);*/
  69. break;
  70. case 5 : strcpy(stmonth,"May");
  71. /*printf("The month is %s\n",stmonth);*/
  72. break;
  73. case 6 : strcpy(stmonth,"June");
  74. /*printf("The month is %s\n",stmonth);*/
  75. break;
  76. case 7 : strcpy(stmonth,"July");
  77. /*printf("The month is %s\n",stmonth);*/
  78. break;
  79. case 8 : strcpy(stmonth,"Aug");
  80. /*printf("The month is %s\n",stmonth);*/
  81. break;
  82. case 9 : strcpy(stmonth,"Sep");
  83. /*printf("The month is %s\n",stmonth);*/
  84. break;
  85. case 10 : strcpy(stmonth,"Oct");
  86. /*printf("The month is %s\n",stmonth);*/
  87. break;
  88. case 11 : strcpy(stmonth,"Nov");
  89. /*printf("The month is %s\n",stmonth);*/
  90. break;
  91. case 12 : strcpy(stmonth,"Dec");
  92. /*printf("The month is %s\n",stmonth);*/
  93. break;
  94. default : strcpy(stmonth,"Invalid");
  95. /*printf("The month is %s\n",stmonth);*/
  96. break;
  97. } /* end of switch */
  98.  
  99. strcpy(datestring,stdate);
  100. strcat(datestring,stmonth);
  101. strcat(datestring," ");
  102. strcat(datestring,styear);
  103. strcat(datestring,".");
  104. /*printf("%s",datestring);*/
  105.  
  106. }
  107.  
  108. int countdays(int bd, int bm, int by, int cd, int cm, int cy)
  109. {
  110.  
  111. int month,year;
  112.  
  113. int daysalive = 0;
  114.  
  115. /* count the days in whole years */
  116. for (year=by+1;year<cy;year=++year) {
  117. if (year==2000) {
  118. daysalive = daysalive + 365;
  119. /*printf("year is %d, adding 365, daysalive counted so
  120. far is %d\n",year,daysalive);*/
  121. }
  122. else {
  123. if (fmod(year,4)==0) {
  124. daysalive = (daysalive + 366);
  125. /*printf("year is %d, adding 366, daysalive counted
  126. so far is %d\n",year,daysalive);*/
  127. }
  128. else {
  129. daysalive = (daysalive + 365);
  130. /*printf("year is %d, adding 365, daysalive counted
  131. so far is %d\n",year,daysalive);*/
  132. }
  133. }
  134. }
  135. /*printf("%d\n",daysalive);*/
  136.  
  137. /* days in whole months this year */
  138. for (month=cm-1;month>0;--month) {
  139. daysalive = (daysalive + (monthswitch(month,year)));
  140. /*printf("adding %d, month is
  141. %d\n",(monthswitch(month,year)),month);*/
  142. }
  143. /*printf("%d\n",daysalive);*/
  144.  
  145. /* days so far in the current month */
  146. daysalive = (daysalive + cd);
  147. /*printf("%d\n",daysalive);*/
  148.  
  149. /* days in whole months in birth year */
  150. for (month=bm+1;month<13;++month) {
  151. daysalive = (daysalive + (monthswitch(month,year)));
  152. }
  153. /*printf("%d\n",daysalive);*/
  154.  
  155. /* days in birth month */
  156. daysalive = (daysalive + (monthswitch(bm,by)) - bd);
  157. /*printf("%d\n",daysalive);*/
  158.  
  159. return daysalive;
  160.  
  161. }
  162.  
  163. int monthswitch(int month,int year) {
  164. switch (month) {
  165. case 4 :
  166. case 6 :
  167. case 9 :
  168. case 11 :
  169. case 12 : dim = 30;
  170. break;
  171. case 1 :
  172. case 3 :
  173. case 5 :
  174. case 7 :
  175. case 8 :
  176. case 10 : dim = 31;
  177. break;
  178. case 2 :
  179. if (year==2000) {
  180. dim = 28;
  181. break;
  182. }
  183. if (fmod(year,4)==0) {
  184. dim = 29;
  185. break;
  186. }
  187. else
  188. dim = 28;
  189. break;
  190. }
  191. return dim;
  192. }
  193.  
  194. main(void)
  195. {
  196.  
  197. int bdate,bmonth,byear;
  198.  
  199. printf ("Please enter your birth date (d/m/yyyy):\n");
  200. scanf  ("%d/%d/%d",&bdate,&bmonth,&byear);
  201. printf ("Your date of birth is
  202. %s\n\n",speakdate(bdate,bmonth,byear));
  203.  
  204. int cdate,cmonth,cyear;
  205.  
  206. printf ("Please enter the current date (d/m/yyyy):\n");
  207. scanf  ("%d/%d/%d",&cdate,&cmonth,&cyear);
  208. printf ("The current date is:
  209. %s\n\n",speakdate(cdate,cmonth,cyear));
  210.  
  211. printf ("Congratulations! You were born a total of %d days
  212. ago.\n",countdays(bdate,bmonth,byear,cdate,cmonth,cyear));
  213.  
  214. }
  215.  
Apr 30 '06 #1
18 3119

be*********@gma il.com wrote:
Hi,

I have just written a simple program to get me started in C that
calculates the number of days since your birthdate.
One thing that confuses me about the program (even though it works) is
how global variables and function returns work...

For example, I have a global array "char datestring[80];" which is
defined in the function speakdate. speakdate just converts a set of
integers (date variables) to a string.

The main program then does:
"printf ("The current date is:
%s\n\n",speakda te(cdate,cmonth ,cyear));"

And correctly prints the value of datestring.
What I don't get is why this works since I haven't explicitly told
speakdate to return datestring.
I figured by default it would return nothing at all.


By default, it returns an int. I'm not certain, but I believe what is
happening is that the return value of the last strcat is being returned
from speakdate. strcat is returning a char *, and the char * is being
cast to an int. You're program is working because on your machine int
and char * probably have the same size.

To avoid this problem, you should explicitely specify the return type
of the function, and explicitely return a value.

Apr 30 '06 #2
[snips]

On Sat, 29 Apr 2006 23:52:57 -0700, ben.carbery wrote:
Full code below. By the way any other tips on my code would be welcomed
and appreciated!

You said "full code" - but I don't see the proper includes here.
char datestring[80];
/* dim is 'days in month'*/
int dim;

speakdate(int d, int m, int y)
What type is being returned? If you meant "nothing", specify void.
strcpy(datestri ng,stdate);
strcat(datestri ng,stmonth);
At the end of the function, the global datestring has a date. So far so
good.

int countdays(int bd, int bm, int by, int cd, int cm, int cy) {

int month,year;

int daysalive = 0;

/* count the days in whole years */
for (year=by+1;year <cy;year=++year ) {
You probably don't want year=++year, but simply ++year
if (fmod(year,4)== 0) {
At a guess, you simply want the modulus operand - % - here.
main(void)
int main(void)
{

int bdate,bmonth,by ear;

printf ("Please enter your birth date (d/m/yyyy):\n"); scanf
("%d/%d/%d",&bdate,&bmo nth,&byear); printf ("Your date of birth is %s\n\n",speakda te(bdate,bmonth ,byear));
speakdate(), as written, returns nothing, so treating it as if it does is
an error. That you get any output at all is simply a matter of accident.
printf ("Congratulatio ns! You were born a total of %d days
ago.\n",countda ys(bdate,bmonth ,byear,cdate,cm onth,cyear));
[/code]


No close brace, no return. Despite the claim of "full code below",
there's no way this could be the full code, as it cannot compile.

That said, you should also turn your compiler's warning level to maximum,
and pay attention to the warnings.
Apr 30 '06 #3
I think I did this since I couldn't figure out how to return a string.

"char speakdate(int d, int m, int y) {" works ok, but

"char[whatever] speakdate(int d, int m, int y) {" didn't.

Is there another syntax to use here?

Apr 30 '06 #4
Thanks for the detailed response!
speakdate(int d, int m, int y)
What type is being returned? If you meant "nothing", specify void.
As per last reply, I want to return a string, but am not sure of the
syntax for returning arrays...
if (fmod(year,4)== 0) {

At a guess, you simply want the modulus operand - % - here.
so... "if((year%4)==0 )" ?
int main(void)
on a related note, is there a difference between "int main (void)" and
"int main ()" ?
speakdate(), as written, returns nothing, so treating it as if it does is
an error. That you get any output at all is simply a matter of accident.
should be able to fix this if i can return an array.
there's no way this could be the full code, as it cannot compile.


Hmmm, this was the full code I was using, compiling ok with bloodshed
dev-c++ on windows (a gcc based compiler). Can't see anything obvious
to raise the logging level, or to expert stricter code...

Apr 30 '06 #5

be*********@gma il.com wrote:
Thanks for the detailed response!
speakdate(int d, int m, int y)

What type is being returned? If you meant "nothing", specify void.


As per last reply, I want to return a string, but am not sure of the
syntax for returning arrays...


You can't return an array, but you can return a pointer to the first
entry.
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 256

char * foo(void)
{
static char ret[MAX_LENGTH];
strncpy(ret, "test", MAX_LENGTH);
return ret;
}

int main(void)
{
printf("%s\n", foo());
return 0;
}

Apr 30 '06 #6
On Sun, 30 Apr 2006 11:50:11 UTC, be*********@gma il.com wrote:
I think I did this since I couldn't figure out how to return a string.

"char speakdate(int d, int m, int y) {" works ok, but


char *speakdate(int d, int m, int y);

will do the trick. You should return a pointer the the string you've
builded.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Apr 30 '06 #7
On Sun, 30 Apr 2006 12:02:11 UTC, be*********@gma il.com wrote:
int main(void)
on a related note, is there a difference between "int main (void)" and
"int main ()" ?


Yes. int main(void) declares a function returning nothing and having
no parameters. int main() declares a function returning nothing and
having an unspecified number of parameters of unspecified types.
speakdate(), as written, returns nothing, so treating it as if it does is
an error. That you get any output at all is simply a matter of accident.


should be able to fix this if i can return an array.


There is no need to return an array. Return a pointer to the string
you've builded already is all you needs. The string should not be an
auto variable becauser that will get indertimine with the return
statement. But using either a static array, a malloced memory area
(the calle would be required to free() it) or extern or at file scope.
--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Apr 30 '06 #8

Herbert Rosenau wrote:
On Sun, 30 Apr 2006 12:02:11 UTC, be*********@gma il.com wrote:
int main(void)


on a related note, is there a difference between "int main (void)" and
"int main ()" ?


Yes. int main(void) declares a function returning nothing and having
no parameters. int main() declares a function returning nothing and
having an unspecified number of parameters of unspecified types.


int main(void) declares a function returning int. void foo(void)
declares a function named foo that takes no arguments and has no return
value. foo(void) implicitly declares a function which takes no
arguments and returns an int (failing to specify a return value is poor
practice and highly frowned upon.)

Apr 30 '06 #9
Herbert Rosenau wrote:
On Sun, 30 Apr 2006 12:02:11 UTC, be*********@gma il.com wrote:
int main(void)

on a related note, is there a difference between "int main (void)" and
"int main ()" ?


Yes. int main(void) declares a function returning nothing and having
no parameters. int main() declares a function returning nothing and
having an unspecified number of parameters of unspecified types.


You mean returning an int, not returning nothing.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
Apr 30 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

34
2428
by: kevin.watters | last post by:
Hi all, I have a need for a short program: Given a drive letter, it would recursively search through all directories, "generating" each filename that it encounters (need to pass each filename to a function). Can't help but think this "utility" already exists but f**ked if I can find it.
4
1798
by: bienwell | last post by:
Hi all, I'd like to use TRY, CATCH to open my database connection. I have 2 servers that have the same table name "myTable". If the first connection to Server1 is failed, then the program will try to connect to Server2. Can I have the secong Try inside the first Catch for this purpose ?. Please take a look on my code and fix it if possible. Actually with this code, the database connection with Server2 is opened after the first...
4
2381
by: News | last post by:
Hi Everyone, The attached code creates client connections to websphere queue managers and then processes an inquiry against them. The program functions when it gets options from the command line. It also works when pulling the options from a file.
36
3185
by: Chuck Faranda | last post by:
I'm trying to debug my first C program (firmware for PIC MCU). The problem is getting serial data back from my device. My get commands have to be sent twice for the PIC to respond properly with the needed data. Any ideas? Here's the code in question, see any reason why a command would not trigger the 'kbhit' the first time a serial command is sent?: Thanks! Chuck **************************************************** while(1) //...
16
4807
by: Martin Joergensen | last post by:
Hi, I wanted to try something which I think is a very good exercise... I read in data from the keyboard and store them in a structure. There's a pointer called "data_pointer" which I use to keep track on the structures... But it's a bit confusing - my program won't compile and I don't know what to do about the warnings/error messages. c:\documents and settings\dell\Desktop\test\main.c(5) : warning
7
2168
by: Buck Rogers | last post by:
Hi all! Newbie here. Below is an example from Teach Yourself C in 21 Days. My apologies if it is a bit long. What I don't understand is how the "get_data" function can call the "continue_function", and if NO is returned to "get_data", display_report executes and the program ends? Basically I am having trouble understanding the program flow within the "if" loop in the "main" function.
20
2599
by: Francine.Neary | last post by:
I am learning C, having fun with strings & pointers at the moment! The following program is my solution to an exercise to take an input, strip the first word, and output the rest. It works fine when you give it 2 or more words, but when there's only 1 word the results vary depending on whether it's on Windows or Linux: under MSVC it displays no output (as it should); under gcc/Linux it instead gives "Segmentation fault". Any ideas...
3
419
by: cs | last post by:
Hi, I'm new to C and would appreciate any feedback on the following program, asplit, which splits a file into 2 new files, putting a certain number of lines in the first file, and all the rest in the second file. Any comments as to non-portability, stylistic infelicities, outright bugs or anything else would be very much appreciated.
8
1497
by: oh.i.love.spam | last post by:
I've been a procedural PHPer for a while now and I don't know why it has taken me so long to start the jump from procedural to OOP. I have a function that I would use for doing length conversions... feet to meters, inches to centimeters, etc... and I wanted to try and turn that into a useful class just for some OOP practice, but I don't think it was a very good start. Maybe it was a bad function to begin with... but I'm not seeing how...
0
8428
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8423
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8076
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8290
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6749
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5446
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2438
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1546
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1274
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.