tags:

views:

184

answers:

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

static struct tm createDate(unsigned day, unsigned mon, int year) {
       struct tm b = {0,0,0,day,mon-1,year-1900}; return b; 
}

static int dateExceeded(unsigned day, unsigned mon, int year) {
    struct tm b = createDate(day,mon,year); 
    time_t y = mktime(&b), now; 
    time(&now);  // error C2143: syntax error : missing ';' before 'type'
    double diff = difftime(y, now) / (60 * 60 * 24);  // error C2065: 'diff' : undeclared identifier
    return (diff < 0); 
}

static void randomEvent(){
    srand(time(NULL));
    if ( rand()%10) {
            printf("Do something here\n"); // C2143: syntax error : missing ';' before 'type'
  } 
}
+5  A: 

If you are compiling this as C89 code, you should declare variables at the beginning of blocks. You can't declare double diff at the middle of the block:

static int dateExceeded(unsigned day, unsigned mon, int year) {
    double diff;
    struct tm b = createDate(day,mon,year); 
    time_t y = mktime(&b), now; 
    time(&now); 
    diff = difftime(y, now) / (60 * 60 * 24);
    return (diff < 0); 
}
Mehrdad Afshari
A: 

Hmm, I don't seem to be able to reproduce this. Using your exact code:

1>------ Build started: Project: so_1251288, Configuration: Debug Win32 ------
1>Compiling...
1>so_1251288.cpp
1>c:\users\matthew iselin\documents\visual studio 2008\projects\so_1251288\so_1251288\so_1251288.cpp(21) : warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>Linking...
1>Build log was saved at *snip*
1>so_1251288 - 0 error(s), 1 warning(s)
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

I assumed you're using Visual C++. What version are you using? What's your environment configured as?

The only thing I can think of is that you may have unintentionally enabled Unicode rather than Multibyte character encoding... But that shouldn't cause the errors you're seeing.

EDIT: I can't even reproduce by creating a Visual C++ CLR application and directly pasting your code. We need some more information to be able to diagnose the problem.

EDIT 2: Actually, I can reproduce, when I compile as C (/TC) rather than C++ (/TP) code. As has been already mentioned, C89 requires variables to be defined at the beginning of functions, which causes your code to fail.

Matthew Iselin
Compile it as C code (not C++) and you'll see.
Mehrdad Afshari
Yup, I tested that right after I read your answer :)
Matthew Iselin
+1  A: 

There is also a mistake in the code. You should call srand only once in the program's lifetime. If you call srand every time before rand(), it may happen that you get the same values over and over again.

Tamás Szelei
A: 
ISO C90 forbids mixed declarations and code