user1094566
user1094566

Reputation: 67

time.h works in C++ not in C

The code:

#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
#include "time.h"
int main()
{
    time_t start, end;
    time (&start);
    int i;
    double dif;
    /*int serie[100000];*/
    /* int *serie = malloc( sizeof(int) );

    for (i = 0; i <= 100000; i++) {
        *serie(i)=rand();
        printf("%d \n", serie[i]);
    }
    */
    time (&end);
    dif = difftime (end, start);

    printf ("Time of execution is: %f\n", dif );

    getchar();

    return 0;

}

The Introduction: (no need to read it)

I knew a bit of C++ from about 3 years ago. I have decided to learn C to create a "fast" subset sum algorithm. This was a simple program to learn C. The problem is to create random numbers and time it. This code actually works when I compiled as default or C++ with Visual Studio, but I decided to do it in C and I wanted to create a dynamic array.

It seems that there is no new in C. We have to use malloc, but to compile malloc I think it has to be compiled in C. In C++, it gives me this error:

cannot convert from 'void *' to 'int *'

Anyway, it happens that I decided to write in C, so it seems logical to compile in C. I have chosen the time function to measure the program, I like it more than clock because I do not know how many processors are working.

The question:

The code as it is above with the comments compiles perfectly in C++, but in C it doesn't compile. Specifically, this line:

time (&start);

gives me this error:

syntax error : missing ';' before 'type'

I just want to compute the start time and the end time and then subtract them with difftime as I have successfully done in C++.

Upvotes: 3

Views: 1966

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54393

I bet that your C compiler is defaulting to the rule that variable declarations must be at the beginning of a block.

You have your call to time(&start) before int i. This is OK in C++ but not in C. To be specific, all variables must be declared before any program code in all versions of C until C99. In the 1999 C Standard, the rule changed to be like C++ and you can mix code and variable declarations.

If you have a C99 compiler or a compiler option that does allow C99 rules, still don't do it, because it isn't reliably portable. And even in C99 there are not many good reasons to mix variables and code anyway. The only one I can think of is a C99 variable length array that requires code to calculate the desired length.

Upvotes: 7

Related Questions