user133466
user133466

Reputation: 3415

syntax error : 'type'

int max(int N, ...){
    int* x = &N;
    x = x + 1;
    int max = x[1];
    for(int k = 1; k < N ; k += 1){
        if(x[k] > max) {max = x[k];}
    }
    return max;
}

void main(){
    //printf("%d", max(3));

}

I've tried compiling the above code from an key solution, but Im getting the error syntax error : 'type' What's going on...

Upvotes: 0

Views: 2304

Answers (4)

AndersK
AndersK

Reputation: 36082

Your x = x + 1 does not do what you expect.

You need to use stdarg.h in order to handle variable arguments.

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 753675

This is one way to do it:

#include <stdarg.h>
#include <limits.h>

int max(int N, ...)
{
    int big = INT_MIN;
    int i;
    va_list args;

    va_start(args, N);
    for (i = 0; i < N; i++)
    {
        int x = va_arg(args, int);
        if (big < x)
            big = x;
    }
    va_end(args);
    return(big);
}

#include <stdio.h>
int main(void)
{
    printf("%d\n", max(6, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(5, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(4, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(3, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(2, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(1, 1, 3, 5, 7, 9, 8));
    printf("%d\n", max(0, 1, 3, 5, 7, 9, 8));
    return(0);
}

Upvotes: 1

Xolve
Xolve

Reputation: 23200

Compiles well in gcc

gcc foo.c -std=c99

the option to set is as c99 so that for loop counter declared goes well.

Upvotes: 0

caf
caf

Reputation: 239031

It sounds like you are using a C89 compiler. That code is written for a C99 or C++ compiler - to convert it, you need to move the declarations of max and k to the top of the function.

Upvotes: 2

Related Questions