Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this valid C code

Tags:

c

This does what I want but I don't recall seeing it anywhere before and was wondering if it's undefined behavior or is correct. I'm referring to how I pass the short to f().

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

void f(short *s)
{
   printf("%d\n",s[0]);
}

int main(int argc, char *argv[])
{
    f((short[5]){0,1,1,1,1});
}
like image 450
user740521 Avatar asked Apr 25 '26 01:04

user740521


1 Answers

Yes, this is valid. The construction is called a compound literal, and was introduced in C99. Like any other literal, it's just a way to create a temporary array, for instance to pass to a function as in this example, without actually creating a variable.

like image 157
Crowman Avatar answered Apr 27 '26 20:04

Crowman