Home > front end >  Disregarding more particular ISA's, is it incorrect to use char argc instead of int argc
Disregarding more particular ISA's, is it incorrect to use char argc instead of int argc

Time:09-02

For example, on an x86 architecture, where chars are represented as 1 byte, as long as you don't have more than 127 or 255 (depending on how its represented) arguments passed on the stack, shouldn't this be possible. Could this cause issues with alignment for the stack since argv would be 8 bytes to argc's 1 byte vs 8 bytes to argc's 4 bytes?

Is this incorrect, or does it depend on implementation and application

int main(char argc, char **argv)

CodePudding user response:

For it to be meaningful to ask whether some code is correct or incorrect, there must be a set of rules to judge it against. The C standard alone is voluntary; no person or product is automatically required to conform to it. If your employer or customer wants you to produce C code that is portable according to the C standard, then that is a rule we can use to judge, and then it is incorrect to declare main as int main(char argc, char **argv[]), as the behavior would not be defined by the C standard. It might work in some C implementations and fail in others.

In Application Binary Interfaces (ABIs) commonly used in the IA-32 (“x86”) architecture or the Intel 64 architecture (“x86-64”), this would not cause a stack alignment issue because both arguments would be passed in registers. If you get it to compile (GCC 12.2 will, Apple Clang 11.0 will not), I suspect it will “work.”

With an ABI that passed arguments on the stack, this could indeed mess up the stack.

CodePudding user response:

is it incorrect to use char argc instead of int argc

Maybe.

C allows various argument parameter sets with main() with "... or in some other implementation-defined manner.". char argc would not be outright non-conforming as it may be allowed on that implementation, but certainly not a portable usage as ... main(char argc, ...) is not regularly allowed. If an implementation allows ... main(char argc, ...), it is OK, else it it not.


Could this cause issues with alignment for the stack since argv would be 8 bytes to argc's 1 byte vs 8 bytes to argc's 4 bytes?

Detail: argc is not certainly 4-bytes as an int may differ from 4 bytes. Pointers are not certainly 8 bytes.

If ... main(char argc, ...) was valid for a given implementation, there is no alignment issue. If ... main(char argc, ...) is not valid, then alignment is not the concern as that function signature is not valid.


Is this incorrect, or does it depend on implementation and application

If the (compiler) implementation allows it it is OK, else it is not correct. It is not depend on the application, but dependent on the implementation.

  •  Tags:  
  • c c
  • Related