0

I am following the C primer plus and encounter the following example:

#include <stdio.h>
#include <string.h> //provide strlen() prototype
#define PRAISE "You are an extraordinary being with a big big brain."
int main(void)
{
    char name[40];

    printf("What's your name? ");
    scanf("%s", name);
    printf("Hello, %s. %s\n", name, PRAISE);
    printf("Your name of %zd letters occupies %zd memory cells.\n", strlen(name), sizeof name);
    printf("Size of the name %zd", sizeof(name));

    return 0;
}

Compiled and run it:

$ ./a.out
What's your name? Trump
You are an extraordinary being with a big big brain."
Your name of 5 letters occupies 40 memory cells.
Size of the name 40

What puzzled me is that sizeof(name) is identical to sizeof name?

sizeof() is a library routine, but how abut sizeof, it seems as predicate and parameter as it was in command line.

Hasturkun
  • 33,910
  • 5
  • 73
  • 99
AbstProcDo
  • 17,381
  • 14
  • 68
  • 114
  • 2
    So rude. My name is `abcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvxyzabcdefghijklmnopqrstuvwxyz` and I get a segfault from your program :( – hellow Oct 15 '18 at 09:25
  • adding to what @Jabberwocky said, parenthesis **are** needed when evaluating the size of a type, for example `sizeof (char)` – Kovalainen Oct 15 '18 at 09:26
  • I like to think of it as the parenthesis "belonging" to the type (pretty much like a cast). Some people overdo the parenthesis thing though (`sizeof (a)`, `return (42);`, ...) – pmg Oct 15 '18 at 09:28

2 Answers2

4

No sizeof isn't a library function, it's a special operator keyword.

It has two forms: One is with parentheses to get the size of a type. The other is not using parentheses and is for getting the size of the result of a generic expression.

With sizeof(name) you're really using the second variant, with the expression (name). I.e. the parentheses are part of the expression and not the sizeof operator.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
3

The sizeof operator (not function) yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type.

It can be used with or without parentheses if the operand is an expression.
It can only be used with parentheses if it is a type.

So in your case, sizeof(name) and sizeof name are both valid.
But something like sizeof char would be invalid, whereas sizeof(char) would be valid.

P.W
  • 25,639
  • 6
  • 35
  • 72