1

I am new to programming and on learning dynamic typing in python, it arisess a doubt in "static typing". I tried out this code (assigning a string to an integer variable which was previously declared) and printing the variable as printf(var_name) and its gives output; can anyone explain this concept?

#include<stdio.h>
#include<conio.h>
void main()
{
    int i = 20 ;
    i = "hello";
    printf(i);
}
Milo
  • 3,365
  • 9
  • 30
  • 44
Dheepak L
  • 13
  • 3
  • 2
    Possible duplicate of [Is C strongly typed?](https://stackoverflow.com/questions/430182/is-c-strongly-typed) – Superlokkus Jan 18 '19 at 14:13
  • 1
    You should enable warnings in your compiler. For GCC try `-Wall -Wextra`. You should get some warning "Make integer from pointer" or similar. The string literal decays to type `char *` which is a 32 or 64 bit pointer. The numerical value of that pointer is then assigned to a probably 32 bit integer. Then again you provide an integer to `printf` which expects to get a `char *`. If addresses are longer than integers, you lost half of the address in this weird conversion. Don't do it! The success relies on some implementation defined behaviour. – Gerhardh Jan 18 '19 at 14:20

1 Answers1

4

Besides your question might be a duplicate, let me append something missing of the read worthy answer https://stackoverflow.com/a/430414/3537677

C is strongly/statically typed but weakly checked

This is one of the biggest core language features which sets C apart from other languages like C++. (Which people are used to mistake a simply "C with classes"

Meaning although C has a strong type system in the context of needing and using it for knowing sizes of types at compile time, the C languages does not have a type system in order to check them for misuse. So compilers are neither mandated to check it nor are they allowed to error your code, because its legal C code. Modern compilers will issue a warning dough.

C compilers are only ensuring "their type system" for the mentioned size management. Meaning, if you just type int i = 42; this variable has so called automatic storage duration or what many people are calling more or less correctly "the stack". It means the compiler will take care of getting space for the variable and cleaning it up. If it can not know the size of it, but needs it then it will indeed generate an error. But this can be circumvented by doing things at run-time and using of types without any type whats so ever, i.e. pointers and void* aka void-pointers.

Regarding your code

Your code seems to be an old, non standard C compiler judging by the #include<conio.h> and void returning main. With a few modifications one can compile your code, but by calling printf with an illegal format string, you are causing so called undefined behaviour (UB), meaning it might work on your machine, but crashes on mine.

Superlokkus
  • 4,731
  • 1
  • 25
  • 57